October 2021
Intermediate to advanced
500 pages
16h 23m
English
We have said several times now that interfaces focus on the what and not the how. You can, however, provide a default implementation for property getters and functions in an interface. Classes that implement the interface then have the option of using the default or defining their own implementation.
Provide a default implementation for attack in Fightable. This function should take the sum of the dice rolls and deal the corresponding amount of damage.
Listing 17.5 Defining a default implementation (Creature.kt)
import kotlin.random.Random
interface Fightable {
val name: String
var healthPoints: Int
val diceCount: Int
val diceSides: Int
fun takeDamage(damage: Int)
fun attack(opponent: Fightable) {
val ...Read now
Unlock full access