Implementing multiple interfaces

A class can implement multiple interfaces. This is one way in which composition can be achieved in Kotlin. Rather than belonging to strict inheritance hierarchies, all classes can implement interfaces that define specific behaviors.

To add multiple interfaces to the class declaration, separate the interface names by commas, as shown in the following code:

class Player : Movable, Drawable {

override fun update(currentTime: Long) {
// add logic
}

override fun move(currentTime: Long) {
// add logic
}

override fun draw() {
// add logic
}
}

In this example, we've added a Drawable interface to our Player class, which already implements Movable

What happens if two interfaces include the same method signature? In that case, the implementing class needs to define a single overridden method, as follows:

  1. We'll add a method to the Drawable interface, which is identical to a method that already exists in our GameObject interface:
interface Drawable {
fun draw()
fun update(currentTime: Long)
}
  1. In the following snippet, we'll see that, even though both Movable and Drawable define an update() method, it only needs to be overridden once:
class Player : Movable, Drawable {

override fun update(currentTime: Long) {
// add logic
}

override fun move(currentTime: Long) {
// add logic
}

override fun draw() {
// add logic
}
}

After adding an update() method to the Drawable interface that is identical to the GameObject interface, the implementing Player class did not need an update to account for the additional method. This changes slightly if the identical methods include default implementations, which we will look at in the next section.