class PropertyDelete {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return “$thisRef, your deleted property name is ${property.name}”
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
println(“$thisRef, new value is $value”)
}
}
class PropertyClass {
//通过属性委托,不用给 name 赋值,因为其 set 和 get 方法都被委托到了 PropertyDelete 对象
var name: String by PropertyDelete()
}
/**
调用结果
cn.yan.test.PropertyClass@30946e09, new value is 7890
cn.yan.test.PropertyClass@30946e09, your deleted property name is name
*/
fun testRun() {
val test = PropertyClass()
test.name = “7890”
println(test.name)
}
属性委托有四种情况在实际开发中比较常用:
-
延迟属性。
-
非空属性。
-
可观测属性。
-
map 委托。
延迟属性: 属性只有在第一次访问时才会计算,之后则会将之前的计算结果缓存起来供后续调用。如下是一个案例:
//延迟属性:依赖 kotlin 提供的 lazy 函数实现,函数参数是一个 lambada 表达式
//源码 LazyJVM.kt 中 public actual fun lazy(initializer: () -> T): Lazy = SynchronizedLazyImpl(initializer) 方法
val lazyValue: Int by lazy {
println(“lazyValue lazy”)
28
}
/**
调用结果
lazyValue lazy
28
28
*/
fun testRun() {
//首次调用时触发计算
printl