Reputation: 45
In Kotlin, is it possible to have a Delegation chain ? To demonstrate what i'm trying to achieve here's the example (https://kotlinlang.org/docs/reference/delegation.html) in the kotlin doc modified :
interface Base {
fun print()
}
class BaseImpl(val x: Int) : Base {
override fun print() { println(x) }
}
class Derived(var b: Base, val someData: Float = 10f) : Base by b
class SecondDerived(var b: Base) : Base by b
fun main(args: Array<String>) {
val b = BaseImpl(10)
val derived = Derived(b)
val secondDerived: Base = SecondDerived(derived)
secondDerived.print()// prints 10
if (secondDerived is Derived) println(secondDerived.someData) //here secondDerived is Derived == false
}
I would expect "secondDerived" to be of type "Derived" but the cast say it is not.
I suspect that in memory the secondDerived base is indeed of type Derived, but the compiler cannot see that. Is there any way to make the cast work ?
Upvotes: 1
Views: 361
Reputation: 97148
On the JVM, a class can have only a single superclass, and Kotlin's class delegation does not change it in any way. All it does is generate implementations of Base
interface methods that delegate to the Derived
instance. It does not affect is
checks.
Upvotes: 2