the_kaba
the_kaba

Reputation: 1567

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

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

Answers (2)

stantronic
stantronic

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

hotkey
hotkey

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

Related Questions