简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM