How to Implement Multiple Interfaces in Kotlin Easily
In Kotlin, you implement multiple interfaces by listing them separated by commas after a colon in the class declaration, like
class MyClass: Interface1, Interface2. You must then provide implementations for all abstract members from each interface in your class.Syntax
To implement multiple interfaces in Kotlin, write the class name followed by a colon and list all interfaces separated by commas. Then, override all required functions or properties from those interfaces inside the class.
Example syntax:
class ClassName: Interface1, Interface2 {
override fun methodFromInterface1() { /* implementation */ }
override fun methodFromInterface2() { /* implementation */ }
}kotlin
interface Interface1 {
fun greet()
}
interface Interface2 {
fun farewell()
}
class MyClass: Interface1, Interface2 {
override fun greet() {
println("Hello from Interface1")
}
override fun farewell() {
println("Goodbye from Interface2")
}
}Example
This example shows a class implementing two interfaces, each with one function. The class provides its own versions of these functions and prints messages when called.
kotlin
interface Speaker {
fun speak()
}
interface Mover {
fun move()
}
class Robot: Speaker, Mover {
override fun speak() {
println("Robot says: Hello!")
}
override fun move() {
println("Robot moves forward")
}
}
fun main() {
val robot = Robot()
robot.speak()
robot.move()
}Output
Robot says: Hello!
Robot moves forward
Common Pitfalls
One common mistake is forgetting to override all abstract members from each interface, which causes a compile error. Another is when two interfaces have methods with the same signature; you must explicitly override and specify which implementation to use or provide your own.
kotlin
interface A {
fun show() = println("A's show")
}
interface B {
fun show() = println("B's show")
}
class C: A, B {
override fun show() {
// Must explicitly choose which show() to call or provide new implementation
super<A>.show()
super<B>.show()
println("C's own show")
}
}
fun main() {
val c = C()
c.show()
}Output
A's show
B's show
C's own show
Quick Reference
- Use a comma-separated list of interfaces after the class name.
- Override all abstract members from each interface.
- If interfaces have conflicting methods, override and specify which to call.
Key Takeaways
List multiple interfaces separated by commas after the class name with a colon.
Always override all abstract functions or properties from each interface.
If interfaces have methods with the same name, explicitly override and resolve conflicts.
Use
super to call a specific interface's implementation.Implementing multiple interfaces allows combining behaviors cleanly in Kotlin.