Interface with default implementations
suggest changeAn interface in Kotlin can have default implementations for functions:
interface MyInterface {
fun withImplementation() {
print("withImplementation() was called")
}
}
Classes that implement such interfaces can use those functions without reimplementing them.
class MyClass: MyInterface {
// No need to reimplement here
}
val instance = MyClass()
instance.withImplementation()
Properties
Default implementations also work for property getters and setters:
interface MyInterface2 {
val helloWorld: String
get() = "Hello World!"
}
Implementations of interface accessors cannot use backing fields:
interface MyInterface3 {
// this property won't compile!
var helloWorld: Int
get() = field
set(value) { field = value }
}
Multiple implementations
When more than one interface declares the same function, the derived class must override it and choose which implementation to call:
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 be used normally on instances
// The class must define how to combine the interface functions.
override fun implementedInBoth() {
super<B>.implementedInBoth()
super<A>.implementedInBoth()
}
// Even if there is only one implementation, there are multiple definitions.
override fun implementedInOne() {
super<A>.implementedInOne()
print("implementedInOne class implementation")
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents