Reputation: 1567
Is there any way to get a reference to the delegated object in Kotlin? Here's an example:
interface A {
fun test()
}
class B: A {
override fun test() {
println("test")
}
}
class C: A by B() {
override fun test() {
// ??? how to get a reference to B's test() method?
}
}
Upvotes: 7
Views: 361
Reputation: 405
Another workaround to hotkey's answer might be to include a delegate value on the A interface...
interface A {
val delegate: A
fun test()
}
class B: A {
override val delegate get() = this
override fun test() {
println("test")
}
}
class C: A by B() {
override fun test() {
delegate.test()
}
}
... this is useful for when zero-arg constructors are required by a framework, e.g. Android Activities
Upvotes: 0
Reputation: 147941
There's currently no way to do that directly. You can achieve that by storing it in a property declared in the primary constructor as follows:
class C private constructor(
private val bDelegate: B
) : A by bDelegate {
constructor() : this(B())
/* Use bDelegate */
}
Upvotes: 12