Chota Bheem
Chota Bheem

Reputation: 1116

Set and Get the class field(s) using Delegate in Kotlin

How to use Delegate for class field getters & setters? Trying to set and get fields(may be some more execution while getting & setting) in Kotlin.

import kotlin.reflect.KProperty

class Example {
    var p: String by Delegate()

    override fun toString(): String {
        return "toString:" + p
    }
}

class Delegate() {
    operator fun getValue(thisRef: Any?, prop: KProperty<*>): String {
        //Something like this :prop.get(thisRef)
       return "value"
    }

    operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) {

        //something like this : prop.set(thisRef, value)
    }
}

fun main(args: Array<String>) {
    val e = Example()
    println(e.p)//blank output
    e.p = "NEW"
    println(e.p)//NEW should be the output
}

Tutorial : https://try.kotlinlang.org/#/Examples/Delegated%20properties/Custom%20delegate/Custom%20delegate.kt

Upvotes: 4

Views: 1425

Answers (1)

zsmb13
zsmb13

Reputation: 89548

You don't get a backing field for your delegate's value by default, because it might not store an actual value, or it may store many different values. If you want to store a single String here, you can create a property for it in your delegate:

class Delegate {
    private var myValue: String = ""

    operator fun getValue(thisRef: Any?, prop: KProperty<*>): String {
        return myValue
    }

    operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) {
        myValue = value
    }
}

Upvotes: 7

Related Questions