Kotlin 中 by 关键字用来简化实现代理 (委托) 模式,不仅可以类代理,还可以代理类属性, 监听属性变化,下面我们来介绍by的几种主要使用场景:
- 类的代理 class
- 属性延迟加载 lazy
- 可观察属性 Delegates.observable ( 扩展 Delegates.vetoable )
- 自定义监听属性变化 ReadWriteProperty
- 属性非空强校验 Delegates.notNull()
- Map值 映射到类属性 map
类的代理(代理/委托模式)
class ByTest {
// 定义一个接口,和一个方法 show()
interface Base {
fun show()
}
// 定义类实现 Base 接口, 并实现 show 方法
open class BaseImpl : Base {
override fun show() {
AbLogUtil.e("BaseImpl::show()")
}
}
// 定义代理类实现 Base 接口, 构造函数参数是一个 Base 对象
// by 后跟 Base 对象, 不需要再实现 show()
class BaseProxy(base: Base) : Base by base {
fun showOther() {
AbLogUtil.e("BaseImpl::showOther()")
}
}
// main 方法
fun mainGo() {
val base = BaseImpl()
BaseProxy(base).show()
BaseProxy(base).showOther()
}
}
输出结果
BaseImpl::show()
BaseImpl::showOther()
转成 Java 代码
public interface Base {
void show();
}
// BaseImpl.java
public class BaseImpl implements Base {
public void show() {
String var1 = "BaseImpl::show()";
System.out.print(var1);
}
}
// BaseProxy.java
public final class BaseProxy implements Base {
// $FF: synthetic field
private final Base $$delegate_0;
public BaseProxy(@NotNull Base base) {
Intrinsics.checkParameterIsNotNull(base, "base");
super();
this.$$delegate_0 = base;
}
public void show() {
this.$$delegate_0.show();
}
}
// NormalKt.java
public final class NormalKt {
public static final