July 2018
Intermediate to advanced
400 pages
12h 14m
English
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 ...