委托模式已經(jīng)證明是實現(xiàn)繼承的一個很好的替代方式,
而 Kotlin 可以零樣板代碼地原生支持它。
類 Derived 可以繼承一個接口 Base,并將其所有共有的方法委托給一個指定的對象:
interface Base {
fun print()
}
class BaseImpl(val x: Int) : Base {
override fun print() { print(x) }
}
class Derived(b: Base) : Base by b
fun main(args: Array<String>) {
val b = BaseImpl(10)
Derived(b).print() // 輸出 10
}
Derived 的超類型列表中的 by{: .keyword }-子句表示 b 將會在 Derived 中內(nèi)部存儲。
并且編譯器將生成轉(zhuǎn)發(fā)給 b 的所有 Base 的方法。