Since multiple inheritance is not allowed in java/kotlin, it's usefull to take advantage of interface default methods. Given example:
abstract class Animal {
fun beAnimal() {
println("I'm animal!")
}
}
abstract class Mammal : Animal() {
fun produceMilk() {
beAnimal().apply { println("Freesh milk!") }
}
}
abstract class AnimalWithBeak : Animal() {
fun quack() {
beAnimal().apply { println("Quack!") }
}
}
class Platypus : ??? // I want it to both produce milk and quack!
As noted above, multiple base classes are not allowed, but we can use interfaces:
abstract class Animal { fun beAnimal() { println("I'm animal!") } }
interface Mammal {
fun produceMilk() {
(this as Animal).beAnimal().apply { println("Freesh milk!") }
}
}
interface AnimalWithBeak {
fun quack() {
(this as Animal).beAnimal().apply { println("Quack!") }
}
}
class Platypus : Animal(), Mammal, AnimalWithBeak {
fun bePlatypus() {
quack() // ok
produceMilk() // ok
}
}
Note that I don't own Animal
class, but I still want to subclass it, and be able to mix these implementations. Example above is really simple, but in real code it would be extremely useful.
The problem is, that class that doesn't extend Animal
can implement Mammal
and AnimalWithBeak
interfaces. In this case, the code will be broken as this as Animal
cast will fail.
So the question - Is it possible to constraint interface inheritance only to specific classes? In this case, only classes that extend Animal
should be allowed to implement Mammal
and AnimalWithBeak
interfaces.
Abstract syntax that probably doesn't exist could look something like that:
interface Mammal where this : Animal
But I quess it's not valid. Any solutions?