Kotlin中的接口可以具有功能的默认实现:
interface MyInterface {
fun withImplementation() {
print("withImplementation() was called")
}
}实现此类接口的类将能够使用这些功能而无需重新实现
class MyClass: MyInterface {
// 无需在这里重新实现
}
val instance = MyClass()
instance.withImplementation()默认实现也适用于属性获取器和设置器:
interface MyInterface2 {
val helloWorld
get() = "你好,世界!"
}接口访问器实现不能使用后备字段
interface MyInterface3 {
// 此属性将无法编译!
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() // 仅定义
}
class MyClass: A, B {
override fun notImplemented() { print("Normal implementation") }
// 可以在实例中正常使用ImplementedOnlyInA()
// 类需要定义如何使用接口函数
override fun implementedInBoth() {
super<B>.implementedInBoth()
super<A>.implementedInBoth()
}
// 即使只有一个实现,也会有多个定义
override fun implementedInOne() {
super<A>.implementedInOne()
print("implementedInOne class implementation")
}
}