Junior
How is an interface implemented in Kotlin and what are the limitations when using it?
sobes.tech AI
Answer from AI
In Kotlin, interfaces are declared using the interface keyword. They can contain declarations of abstract methods as well as implementations of non-abstract methods and properties.
interface MyInterface {
fun abstractMethod() // Abstract method
val abstractProperty: Int // Abstract property
fun nonAbstractMethod() { // Non-abstract method (with default implementation)
println("Default implementation")
}
val nonAbstractProperty: String // Non-abstract property (requires getter)
get() = "Default value"
}
A class implements an interface using the colon operator (:).
class MyClass : MyInterface {
override fun abstractMethod() { // Override abstract method
println("Implementation of abstract method in class")
}
override val abstractProperty: Int = 10 // Override abstract property
// You can choose not to override nonAbstractMethod() and nonAbstractProperty,
// if the default implementation is sufficient.
}
Restrictions:
- Lack of state: Interfaces cannot hold state in the form of instance variables. Properties declared in an interface are either abstract (requiring implementation in the class) or have a getter (possibly with a setter), but no backing fields.
- Multiple inheritance of implementation: A class can implement multiple interfaces, allowing multiple inheritance of behavior. However, if different interfaces provide implementations of the same method with the same signature, the class implementing them must explicitly specify which implementation to use or provide its own.
- Constructors: Interfaces cannot have constructors.
- Visibility: Interface members are
publicby default. They cannot be declared asprivate,protected, orinternalwithin the interface. - Type Aliases: Type aliases cannot be used for interfaces declared in another package.