ClassyPimp
ClassyPimp

Reputation: 725

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

Upvotes: 1

Views: 209

Answers (1)

Muthukrishnan Rajendran
Muthukrishnan Rajendran

Reputation: 11642

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

Upvotes: 2

Related Questions