Kotlin 直接在委托中设置和获取属性
我想这样设置属性并将其传递给委托(或者我应该维护委托本身的状态吗?)Kotlin 直接在委托中设置和获取属性,kotlin,delegation,Kotlin,Delegation,我想这样设置属性并将其传递给委托(或者我应该维护委托本身的状态吗?) 类示例{ var p:String by Delegate() } 类委托(){ 运算符fun getValue(thisRef:Any?,prop:KProperty):字符串{ if(prop/*.getvaluemomegite()*/){/如果您想在getter和setter内部进行一些更改或检查,可以这样做 class Example { var p: String by Delegate() } clas
类示例{
var p:String by Delegate()
}
类委托(){
运算符fun getValue(thisRef:Any?,prop:KProperty):字符串{
if(prop/*.getvaluemomegite()*/){/如果您想在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
}
}
类示例{
var p:String by Delegate()
}
类委托(){
var localValue:字符串?=null
运算符fun getValue(thisRef:Any?,prop:KProperty):字符串{
//这是不可能的。
//如果(prop/*.getvaluemobilize()*/){//
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
}
}