直接在委托中设置和获取属性
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
}
}
我想像这样设置并获取 属性 传递给委托(或者我应该维护委托本身的状态?):
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
}
}