多应用+插件架构,代码干净,支持一键云编译,码云点赞13K star,4.8-4.12 预售价格198元 广告
# 委托 ## 类委托 [委托模式](https://en.wikipedia.org/wiki/Delegation_pattern)已经被证明是实现继承的一个很好的替代选择,Kotlin 原生零样本代码的支持它。类 `Derived` 可以从接口 `Base` 继承并委托它所有的 public 方法给指定的对象: ``` kotlin interface Base { fun print() } class BaseImpl(val x: Int) : Base { override fun print() { print(x) } } class Derived(b: Base) : Base by b fun main() { val b = BaseImpl(10) Derived(b).print() // 打印 10 } ``` `Derived` 超类列表中的 `by` 分支指明 `b` 将存储在 `Derived` 的对象内部并且编译器将生成 `Base` 的所有方法附带给 `b`。