Generics and Variance

Article · 2:00

Writing code that works for any type, and what out and in actually mean.

A generic function or class takes a type as a parameter. List<String> and List<Int> are the same class with different type arguments, and a function declared fun <T> firstOrDefault(items: List<T>, fallback: T): T works for every one of them while still being fully type-checked.

Variance answers a question that looks obvious and is not: if Dog is a Cat... no, if Dog is an Animal, is List<Dog> a List<Animal>? For a read-only list, yes - anything you take out of a list of dogs is an animal. For a mutable list, no - if it were, you could add a cat to a list of dogs through the wider reference and break it later.

Kotlin encodes this in the declaration. out T means T only ever comes out, so the type is covariant and List<Dog> is a List<Animal>. in T means T only ever goes in, so the type is contravariant and a Comparator<Animal> can be used wherever a Comparator<Dog> is wanted. A type parameter with neither is invariant, which is why MutableList is.

A constraint restricts what T can be. Writing <T : Comparable<T>> lets the body call compareTo. Without a constraint, a type parameter is effectively Any? and you can do almost nothing with it.

// A constrained type parameter: T must be comparable with itself
fun <T : Comparable<T>> largest(items: List<T>): T? = items.maxOrNull()

open class Animal(val name: String)
class Dog(name: String) : Animal(name)

// out means T only ever comes out, so this accepts a Producer of any subtype
interface Producer<out T> {
    fun produce(): T
}

fun describeAll(animals: List<Animal>) =
    animals.joinToString { it.name }

fun main() {
    println(largest(listOf(3, 9, 2)))              // 9
    println(largest(listOf("pear", "apple")))      // pear

    val dogs: List<Dog> = listOf(Dog("Rex"), Dog("Bo"))

    // List is declared List<out E>, so this is allowed
    println(describeAll(dogs))                     // Rex, Bo

    // A MutableList<Dog> would NOT be accepted as MutableList<Animal>,
    // because you could then add a non-Dog Animal to it.
}

Discussion

No questions on this topic yet. Sign in to ask the first one.