From what I understand, class delegation is supposed to
allow object composition to achieve the same code reuse as inheritance. [wikipedia]
Kotlin supports Class Delegation, and note the following statement form the documentation:
overrides work as you might expect: The compiler will use your override implementations instead of those in the delegate object.
With this in mind, consider the following minimal example:
interface A {
val v: String
fun printV() {
Logger.getLogger().info(Logger.APP, "A", v)
}
}
class AImpl : A {
override val v = "A"
}
class B(a: A) : A by a {
override val v: String = "B"
}
I expected that B(AImpl()).printV()
would print B
, however instead it prints A
, i.e. it uses the default implementation of AImpl
.
Moreover, if I override the printV()
Method in B using the super
implementation, i.e.
class B(a: A) : A by a {
override val v: String = "B"
override fun printV() {
super.printV()
}
}
I now expected that B(AImpl()).printV()
would print A
, however this time it prints B
.
This seems counterintuitive.
Can you give a good explanation for this behavior?
this::class
instead of v, the first one will beAImpl
and the second one will beB
– Kenric