Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

kotlin

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? 
    }
}
like image 384
the_kaba Avatar asked Sep 09 '18 16:09

the_kaba


1 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 */
}
like image 172
hotkey Avatar answered Sep 20 '22 12:09

hotkey