Kotlin委托了属性,这是一个非常好的功能.但我正在弄清楚如何获取和设置值.假设我想获得委托的财产的价值.在get()方法中我如何访问该值?
这是我如何实现的一个例子:
class Example() {
var p: String by DelegateExample()
}
class DelegateExample {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return "${property.name} "
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
println("${value.trim()} '${property.name.toUpperCase()} '")
}
}
fun delegate(): String {
val e = Example()
e.p = "NEW"
return e.p
}
Run Code Online (Sandbox Code Playgroud)
我无法理解的主要问题是,如何将值设置为分配了委托类的实际属性.当我为属性分配"NEW"时p,如何将该值存储到变量p或读取传递给pget的新值?我错过了一些基本的东西吗?任何帮助都感激不尽.提前致谢.