在Kotlin中使用Delegate设置和获取类字段

时间:2018-06-20 14:51:50

标签: kotlin delegation

如何将Delegate用于类字段的getter和setter?尝试在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
}

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

1 个答案:

答案 0 :(得分:3)

默认情况下,您不会获得代表值的备用字段,因为它可能不存储实际值,或者可能存储许多不同的值。如果要在此处存储单个String,则可以在委托中为其创建属性:

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