Skip to content
配图

属性委托

kotlin
val name: String by lazy { expensive() }
var title: String by observable("") { _, old, new ->
    println("$old -> $new")
}

by viewBinding()(Android)把样板代码收敛到委托。

自定义委托需实现 getValue/setValue 操作符,可嵌入校验、缓存、加密读写的横切逻辑。

委托是 Kotlin 语法糖背后的语义压缩,读懂它可读遍半本 Android 开源库。

Visitors · Page views