Kotlin 的委派 ReadWriteProperty 和 ReadOnlyProperty 简单使用
案例1–自定义ReadWriteProperty,实现Activity/Fragment 成员变量自动回收
案例2–自定义ReadOnlyProperty,实现Activity/Fragment 辅助创建ViewBinding以及自动回收内存
- 先看下ReadWriteProperty 和 ReadOnlyProperty 的源码,源码很简单,就是两个接口。ReadOnlyProperty 有一个getValue方法,ReadWriteProperty 继承了 ReadOnlyProperty ,同时增加了一个setValue方法。
/**
* Base interface that can be used for implementing property delegates of read-only properties.
*
* This is provided only for convenience; you don't have to extend this interface
* as long as your property delegate has methods with the same signatures.
*
* @param T the type of object which owns the delegated property.
* @param V the type of the property value.
*/
public fun interface ReadOnlyProperty<in T, out V> {
/**
* Returns the value of the property for the given object.
* @param thisRef the object for which the value is requested.
* @param property the metadata for the property.
* @return the property value.
*/
public operator fun getValue(thisRef: T, property: KProperty<*>): V
}
/**
* Base interface that can be used for implementing property delegates of read-write properties.
*
* This is provided only for convenience; you don't have to extend this interface
* as long as your property delegate has methods with the same signatures.
*
* @param T the type of object which owns the delegated property.
* @param V the type of the property value.
*/
public interface ReadWriteProperty<in T, V> : ReadOnlyProperty<T, V> {
/**
* Returns the value of the property for the given object.
* @param thisRef the object for which the value is requested.
* @param property the metadata for the property.
* @return the property value.
*/
public override operator fun getValue(thisRef: T, property: KProperty<*>): V
/**
* Sets the value of the property for the given object.
* @param thisRef the object for which the value is requested.
* @param property the metadata for the property.
* @param value the value to set.
*/
public operator fun setValue(thisRef: T, property: KProperty<*>, value: V)
}
- 现在直接看下 ko