案列
package com.yzdzy.kotlin.chapter4.delegates
import kotlin.reflect.KProperty
class Delegates {
val hello by lazy {
"helloWorld"
}
val hello2 by X()
var hello3 by X()
}
class X {
private var value: String? = null
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
println("getValue:$thisRef->${property.name}")
return value ?: "";
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
print("setValue $thisRef->${property.name} = $value")
this.value = value;
}
}
fun main(args: Array<String>) {
val delegates = Delegates()
print(delegates.hello)
print(delegates.hello2)
print(delegates.hello3)
delegates.hello3 = "value of hello3"
println(delegates.hello3)
}
輸出
helloWorldgetValue:com.yzdzy.kotlin.chapter4.delegates.Delegates@4eec7777->hello2
getValue:com.yzdzy.kotlin.chapter4.delegates.Delegates@4eec7777->hello3
setValue com.yzdzy.kotlin.chapter4.delegates.Delegates@4eec7777->hello3 = value of hello3getValue:com.yzdzy.kotlin.chapter4.delegates.Delegates@4eec7777->hello3
value of hello3
定義方法
-
-val/var<property name>:<Type> by <expression>
-
代理者需要實現相應的setValue/getValue方法
-
lazy原理就是屬性代理