Junior
How is the implementation of interfaces carried out in Kotlin?
sobes.tech AI
Answer from AI
Interfaces in Kotlin are implemented using the implements keyword (implicit in Kotlin, simply indicated with a colon) or by for delegation.
Main implementation methods:
- Direct implementation: An object or class directly implements all members of the interface.
When inheriting from a class and implementing interfaces simultaneously, the class is specified first.interface MyInterface { fun doSomething() val myProperty: String } class MyClass : MyInterface { override fun doSomething() { println("Doing something in MyClass") } override val myProperty: String = "Hello" }open class BaseClass class AnotherClass : BaseClass(), MyInterface { override fun doSomething() { println("Doing something in AnotherClass") } override val myProperty: String = "World" } - Delegation of implementation: Interface implementation is delegated to another object. The
bykeyword is used. This is useful for composition and avoiding multiple inheritance issues.In this case,interface DelegatedInterface { fun performAction() } class DelegatedObject : DelegatedInterface { override fun performAction() { println("Action performed by DelegatedObject") } } class ImplementingClass(di: DelegatedInterface) : DelegatedInterface by di { // ImplementingClass delegates the performAction() method to the di object }ImplementingClassdoes not implementperformActionitself; instead, calls toperformingClass.performAction()are forwarded todi.performAction().
When implementing multiple interfaces with members of the same name, conflicts must be explicitly resolved by overriding the member and specifying from which interface the implementation is taken, using the syntax <Interface>.<member>.
interface InterfaceA {
fun foo() { println("InterfaceA") }
fun bar()
}
interface InterfaceB {
fun foo() { println("InterfaceB") }
fun bar() { println("InterfaceB bar") }
}
class ResolvingConflict : InterfaceA, InterfaceB {
override fun foo() {
super<InterfaceA>.foo() // Call the foo implementation from InterfaceA
super<InterfaceB>.foo() // Call the foo implementation from InterfaceB
}
override fun bar() {
super<InterfaceB>.bar() // Use the bar implementation from InterfaceB
}
}