Implementing an Interface
To use an interface, we say that you “implement” it on a class. There are two parts to this: First, you declare that the class implements the interface. Then, you must ensure that the class provides implementations for all the properties and functions specified in the interface.
Use the :
operator to implement the Fightable interface on Player.
Listing 17.2 Implementing an interface (Player.kt
)
class Player( initialName: String, val hometown: String = "Neversummer", override var healthPoints: Int, val isImmortal: Boolean ) : Fightable { override var name = initialName get() = field.replaceFirstChar { it.uppercaseChar() } private set(value) { field = value.trim() } ... }
(We will explain the override ...
Get Kotlin Programming: The Big Nerd Ranch Guide, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.