Search code examples
kotlindelegation

Set and get property directly in delegate


I want to set and get property passed to delegate like this (or should I maintain the state on delegate itself?):

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

Solution

  • If you want to do some change or checking inside getter and setter, can do like this

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