如何在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

声明bval前缀的伎俩:

...导出(VAL B:基地):基地为b .. 。