如何使用委托"by"获取对 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? 
}
}

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

class C private constructor(
private val bDelegate: B
) : A by bDelegate {
constructor() : this(B())
/* Use bDelegate */
}

热键答案的另一种解决方法可能是包含委托值 在 A 接口上...

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()
}
}

。当框架需要零参数构造函数时,这很有用,例如 Android 活动

相关内容

最新更新