October 2021
Intermediate to advanced
500 pages
16h 23m
English
There are cases where it is useful to know the specific type that is used for a generic parameter.
The reified keyword allows you to check a generic parameter’s type.
Suppose that Madrigal is on a quest to collect loot of a specific type. For example, she may want to collect every hat she can get her hands on, ignoring all other types of loot. Here is a takeLootOfType function that attempts to capture that logic:
class LootBox<out T : Loot>(val contents: T) {
var isOpen = false
private set
fun takeLoot(): T? {
return contents.takeIf { !isOpen }
.also { isOpen = true }
}
fun <U> takeLootOfType(): U? {
return if (contents is U) {
takeLoot() as U
} else {
null
}
}
...
}
val lootBox = LootBox.random() ...Read now
Unlock full access