Generic Constraints
At this moment, it is possible to put anything inside your loot box. This is not ideal, because you do not want your hero to be rewarded with a Monster via a loot box. You can ensure that loot boxes are only used to hold loot by specifying a generic type constraint.
Start by introducing an abstract class called Loot and an interface called Sellable in Loot.kt. Then make your loot classes extend from them, as shown in Listing 18.6. (Keys will not be sellable, because nobody would want to purchase a random key.)
Listing 18.6 Adding superclasses (Loot.kt
)
... abstract class Loot { abstract val name: String } interface Sellable { val value: Int } class Fedora( override val name: String, override val value: Int ...
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.