0
点赞
收藏
分享

微信扫一扫

【22】kotlin 属性代理

Just_Esme 2023-03-10 阅读 129


案列

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原理就是属性代理

举报

相关推荐

0 条评论