如何使用委托'by'获取Kotlin中委托实例的引用?

the*_*aba 5 kotlin

有没有办法在Kotlin中获取对委托对象的引用?这是一个例子:

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? 
    }
}
Run Code Online (Sandbox Code Playgroud)

hot*_*key 8

目前没有办法直接这样做.您可以通过将其存储在主构造函数中声明的属性中来实现,如下所示:

class C private constructor(
    private val bDelegate: B
) : A by bDelegate {
    constructor() : this(B())

    /* Use bDelegate */
}
Run Code Online (Sandbox Code Playgroud)