gpt4 book ai didi

kotlin - 直接在委托(delegate)中设置和获取属性

转载 作者:行者123 更新时间:2023-12-02 13:24:26 27 4
gpt4 key购买 nike

我想像这样设置和获取传递给委托(delegate)的属性(或者我应该维护委托(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
}
}

关于kotlin - 直接在委托(delegate)中设置和获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44403772/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com