直接在代表中设置并获取属性

我想设置和获取属性传递给这样的委托(或者我应该维护委托本身的状态?):

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 } }