O'Reilly logo

Kotlin Programming: The Big Nerd Ranch Guide, First Edition by David Greenhalgh, Josh Skeen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required