一、定义一个方法
val/var <变量name>: <类型 Type> by (代理者)表达式
代理者需要实现相应的setValue/getValue 方法
如果是val,只需要设置getValue方法
如果是var,则需要设置setValue/getValue 方法
二、看一个属性代理的例子吧
package net.println.kotlin.chapter4.delegates
import kotlin.reflect.KProperty
/**
* @author:wangdong
* @description:
*/
class Delegates{
//只有第一次访问到的时候,才会去初始化它
// 通过by的方式来声明变量的时候,例如Hello的getValue就会交给lazy这个代理来完成
val hello by lazy {
"HelloBoy"
}
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){
println("setValue, $thisRef -> ${property.name} = $value")
this.value = value
}
}
fun main(args: Array<String>) {
val delegates = Delegates()
println(delegates.hello)
println(delegates.hello2)
println(delegates.hello3)
delegates.hello3 = "hello wdddd"
println(delegates.hello3)
}
哈,结束啦