与默认实现的接口

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")
    }
}