- Kotlin进阶实战
- 沈哲 易庞宙编著
- 12字
- 2025-02-20 21:22:45
5.2 Kotlin的委托模式和委托属性
5.2.1 委托模式
Kotlin在语法层面上支持委托模式,实现起来代码显得更加简洁。下面的几行代码即可完成类的委托,实现跟上面的Java完全一样的功能。

Derived类的构造函数的参数b是一个Base对象,通过关键字by完成委托。Derived类无须再实现print()方法。
由此可见,委托模式是替代继承很好的一个选择。
再举一个例子,定义两个接口Marks和Totals,再分别定义它们的实现类StdMarks、ExcelMarks和StdTotals、ExcelTotals。
最后定义一个Student类,它和Marks、Totals建立委托的关系,Student没有使用任何继承。


执行结果如下:
printed marks calculated and printed totals --------------------------- printed marks and export to excel calculated and printed totals and export to excel