Kotlin 中的“by”關鍵字有什麼作用?
Kotlin 透過引入新的關鍵字“by”來支援設計模式的委派。使用此關鍵字或委派方法,Kotlin 允許派生類透過特定物件訪問介面的所有實現的公共方法。
示例
在示例中,我們將實現另一個類中的基類抽象方法。
interface Base { //abstract method fun printMe() } class BaseImpl(val x: Int) : Base { // implementation of the method override fun printMe() { println(x) } } // delegating the public method on the object b class Derived(b: Base) : Base by b fun main(args: Array<String>) { val b = BaseImpl(10) // prints 10 :: accessing the printMe() method Derived(b).printMe() }
輸出
將產生以下輸出
10
廣告