in and out

To further customize your generic type parameters, Kotlin provides the keywords in and out. To see how they work, create a simple generic Barrel class in a new file called Variance.kt:

Listing 17.15  Defining Barrel (Variance.kt)

class Barrel<T>(var item: T)

To experiment with Barrel, add a main function. In main, define a Barrel to hold a Fedora and another Barrel to hold Loot:

Listing 17.16  Defining Barrels in main (Variance.kt)

class Barrel<T>(var item: T)

fun main(args: Array<String>) {
    var fedoraBarrel: Barrel<Fedora> = Barrel(Fedora("a generic-looking fedora", 15))
    var lootBarrel: Barrel<Loot> = Barrel(Coin(15))
}

While a Barrel<Loot> can hold any kind of loot, the particular instance defined here ...

Get Kotlin Programming: The Big Nerd Ranch Guide, First 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.