How to get a reference to delegated instance in Kotlin using delegation 'by'?

Viewed 261

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? 
    }
}
2 Answers

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 */
}

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

Related