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

时间:2018-09-09 16:18:39

标签: 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? 
    }
}

1 个答案:

答案 0 :(得分:8)

目前尚无法直接做到这一点。您可以通过将其存储在主构造函数中声明的属性中来实现此目标,如下所示:

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

    /* Use bDelegate */
}
相关问题