9.属性代理

2020-07-28  本文已影响0人  学吉他的袁先生

定义-val/var<property name>:<Type> by <expression>
代理者需要实现相应的setValue/getValue方法
如果是val修饰的属性只需要具备getValue()方法
by关键字实际上就是一个属性代理运算符重载的符号,任何一个具备属性代理规则的类,都可以使用by关键字对属性进行代理
可以简单理解为属性的setter、getter访问器内部实现是交给一个代理对象来实现
例如kotlin中内置属性代理lazy,当变量第一次被使用时才进行初始化,可以实现懒加载

val hello by lazy {
    "HelloWorld"
}

自定义属性代理

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
    }
}
var hello3 by X()
fun main() {
    println(hello3)
    hello3="111"
}

打印:
getValue: null -> hello3
setValue, null -> hello3 = 111

上一篇 下一篇

猜你喜欢

热点阅读