與預設實現的介面

Kotlin 中的介面可以具有函式的預設實現:

interface MyInterface {
    fun withImplementation() {
      print("withImplementation() was called")
    }
}

實現此類介面的類將能夠使用這些功能而無需重新實現

class MyClass: MyInterface {
    // No need to reimplement here
}
val instance = MyClass()
instance.withImplementation()

屬性

預設實現也適用於屬性 getter 和 setter:

interface MyInterface2 {
    val helloWorld
        get() = "Hello World!"
}

介面訪問器實現不能使用支援欄位

interface MyInterface3 {
    // this property won't compile!
    var helloWorld: Int
        get() = field
        set(value) { field = value }
}

多個實現

當多個介面實現相同的功能,或者所有介面都使用一個或多個實現進行定義時,派生類需要手動解析正確的呼叫

interface A {
    fun notImplemented()
    fun implementedOnlyInA() { print("only A") }
    fun implementedInBoth() { print("both, A") }
    fun implementedInOne() { print("implemented in A") }
}

interface B {
    fun implementedInBoth() { print("both, B") }
    fun implementedInOne() // only defined
}

class MyClass: A, B {
    override fun notImplemented() { print("Normal implementation") }

    // implementedOnlyInA() can by normally used in instances

    // class needs to define how to use interface functions
    override fun implementedInBoth() {
        super<B>.implementedInBoth()
        super<A>.implementedInBoth()
    }

    // even if there's only one implementation, there multiple definitions
    override fun implementedInOne() {
        super<A>.implementedInOne()
        print("implementedInOne class implementation")
    }
}