![]() |
VOOZH | about |
Interfaces in Kotlin can contain declarations of abstract methods, as well as method implementations. What makes them different from abstract classes is that interfaces cannot store a state. They can have properties, but these need to be abstract or provide accessor implementations.
A Kotlin interface contains declarations of abstract methods, and default method implementations although they cannot store state.
interface MyInterface {
fun bar()
}
This interface can now be implemented by a class as follows:
class Child : MyInterface {
override fun bar() {
print("bar() was called")
}
}An interface in Kotlin can have default implementations for functions:
interface MyInterface {
fun withImplementation() {
print("withImplementation() was called")
}
}
Classes implementing such interfaces will be able to use those functions without reimplementing
class MyClass: MyInterface {
// No need to reimplement here
}
val instance = MyClass()
instance.withImplementation()Default implementations also work for property getters and setters:
interface MyInterface2 {
val helloWorld
get() = "Hello World!"
}
Interface accessors implementations can't use backing fields
interface MyInterface3 {
// this property won't compile!
var helloWorld: Int
get() = field
set(value) { field = value }
}When multiple interfaces implement the same function, or all of them define with one or more implementing, the derived class needs to manually resolve proper call
You can declare properties in interfaces. Since an interface cannot have stated you can only declare a property as abstract or by providing default implementation for the accessors.
When implementing more than one interface that has methods of the same name that include default implementations, it is ambiguous to the compiler which implementation should be used. In the case of a conflict, the developer must override the conflicting method and provide a custom implementation. That implementation may choose to delegate to the default implementations or not.
interface MyInterface {
fun funcOne() {
// optional body
print("Function with default implementation")
}
}Note:
If the method in the interface has its own default implementation, we can use the super keyword to access it.
super.funcOne()