July 2018
Intermediate to advanced
400 pages
12h 14m
English
Generic type parameters also work with functions. That is good news, since there is currently no way for a player to retrieve loot from a loot box.
Time to fix that. Add a function that lets a player fetch the item if and only if the box is open. Track whether the box is open by adding an open property.
Listing 17.3 Adding a fetch function (Generics.kt)
class LootBox<T>(item: T) {
var open = false
private var loot: T = item
fun fetch(): T? {
return loot.takeIf { open }
}
}
Here you define a generic function, fetch, that returns T – the generic type parameter specified on the LootBox class, which is a placeholder for the type of item.
Note that if fetch were defined outside of LootBox, type T would not ...
Read now
Unlock full access