如何在Kotlin中获得委托实例?
问题描述:
我想获得委托类的实例。如何在Kotlin中获得委托实例?
具体而言,在下面的示例中,我想获得传递的Base
- b
的实例,但尝试使用b
时出现错误。
interface Base {
fun print()
}
class BaseImpl(val x: Int) : Base {
override fun print() { print(x) }
}
open class Derived(b: Base) : Base by b {
override fun print() {
printSomethingBefore()
b.print() // b isn't recognized :(
printSomethingAfter()
}
}
*资料来源为例如:https://kotlinlang.org/docs/reference/delegation.html
答
声明b
与val
前缀的伎俩:
...导出(VAL B:基地):基地为b .. 。