in and out

To further customize your generic type parameters, Kotlin provides the keywords in and out. To see how they affect your generic classes, try running the following code in the REPL:

Listing 18.10  Attempting to reassign lootBox (REPL)

var fedoraBox: LootBox<Fedora> = LootBox(Fedora("a generic-looking fedora", 15))
var lootBox: LootBox<Loot> = LootBox(Gemstones(150))

lootBox = fedoraBox
error: type mismatch: inferred type is LootBox<Fedora> but
    LootBox<Loot> was expected
lootBox = fedoraBox
          ^

This result may surprise you. The compiler will not allow you to perform the reassignment of lootBox to fedoraBox.

It might seem like the assignment should have been possible. Fedora is, after all, a descendant of Loot, and assigning ...

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.