Kotlin Q & A

 

Can Kotlin classes implement multiple interfaces?

Yes, Kotlin classes can indeed implement multiple interfaces, offering developers a powerful mechanism to leverage multiple sets of behaviors and contracts within a single class. This feature enhances code flexibility, promotes code reuse, and allows for more modular and maintainable codebases.

Implementing multiple interfaces in Kotlin is achieved by specifying each interface separated by commas after the class declaration. This allows the class to inherit the methods and properties defined in each interface, effectively extending its functionality.

For example:

kotlin

interface Drawable {
 fun draw()
}

interface Clickable {
 fun click()
}

class Button : Drawable, Clickable {
 override fun draw() {
 println("Drawing button")
 }

 override fun click() {
 println("Button clicked")
 }
}

In this example, the Button class implements both the Drawable and Clickable interfaces, providing implementations for the draw() and click() methods, respectively. This allows instances of the Button class to be treated as both drawable objects and clickable objects, facilitating versatile usage within the application.

By supporting multiple interface implementation, Kotlin promotes code modularity and extensibility, enabling developers to compose classes with diverse sets of behaviors and contracts, ultimately leading to more adaptable and scalable software solutions.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Experienced Android Engineer specializing in Kotlin with over 5 years of hands-on expertise. Proven record of delivering impactful solutions and driving app innovation.