[英]Set and get property directly in delegate
我想像这样设置并获取传递给委托的属性(或者我应该维护委托本身的状态吗?):
class Example {
var p: String by Delegate()
}
class Delegate() {
operator fun getValue(thisRef: Any?, prop: KProperty<*>): String {
if (prop/*.getValueSomehow()*/){ //<=== is this possible
} else {
prop./*setValueSomehow("foo")*/
return prop./*.getValueSomehow()*/ //<=== is this possible
}
}
operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) {
prop./*setValueSomehow(someDefaultValue)*/ //<=== is this possible
}
}
如果您想进行一些更改或检查getter和setter内部,可以这样做
class Example {
var p: String by Delegate()
}
class Delegate() {
var localValue: String? = null
operator fun getValue(thisRef: Any?, prop: KProperty<*>): String {
//This is not possible.
// if (prop/*.getValueSomehow()*/){ //<=== is this possible
//
// } else {
// prop./*setValueSomehow("foo")*/
// return prop./*.getValueSomehow()*/ //<=== is this possible
// }
if(localValue == null) {
return ""
} else {
return localValue!!
}
}
operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) {
// prop./*setValueSomehow(someDefaultValue)*/ //<=== is this possible - this is not possible
localValue = value
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.