如何将 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
}
Run Code Online (Sandbox Code Playgroud)
教程:https : //try.kotlinlang.org/#/Examples/Delegated%20properties/Custom%20delegate/Custom%20delegate.kt
默认情况下,您不会获得委托值的支持字段,因为它可能不存储实际值,或者可能存储许多不同的值。如果你想在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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
887 次 |
| 最近记录: |