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

时间:2017-06-07 04:52:29

标签: kotlin delegation

我想设置并将get属性传递给委托(或者我应该在委托本身上维护状态吗?):

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

1 个答案:

答案 0 :(得分:2)

如果你想在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
    }
}