<
Kotlin 中的 by 委托
>
上一篇

Viewbindingpropertydelegate 是怎么处理 fragment 的 viewbinding 的, 为什么不需要手动置空
下一篇

免费使用 gpt 4 之 new bing

by 委托 简介

委托,是一种设计模式,又名代理。

语法:

val/var <属性名称>: <类型> by <表达式>

原理:

by 将变量的 set/get (val变量只有get) 委托给 by 关键字后面的表达式返回的对象的 setValue/getValue 函数

by 后面的被委托对象可以直接实现接口 ReadOnlyProperty(对应val) ReadWriteProperty(对应var), 由被代理对象操作的真实的数据

ReadOnlyProperty

public fun interface ReadOnlyProperty<in T, out V> {
    public operator fun getValue(thisRef: T, property: KProperty<*>): V
}

ReadWriteProperty

public interface ReadWriteProperty<in T, V> : ReadOnlyProperty<T, V> {
    public override operator fun getValue(thisRef: T, property: KProperty<*>): V
    public operator fun setValue(thisRef: T, property: KProperty<*>, value: V)
}

使用 by 可以使用简化很多代码,提高内聚,降低耦合

Kotlin 标准库中的委托

Top
Foot