AI写作智能体 自主规划任务,支持联网查询和网页读取,多模态高效创作各类分析报告、商业计划、营销方案、教学内容等。 广告
# 委托 ## 类委托 [委托模式](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`。