0Pricing
Kotlin Academy · Lesson

Declaration-Site Variance

in and out.

The Variance Problem

Is a List<String> a kind of List<Any>? Sometimes yes, sometimes no. Variance describes how generic types relate when their type parameters relate. Kotlin uses out and in to express this.

Invariance by Default

By default generics are invariant: Box<String> is NOT a Box<Any>, even though String is a subtype of Any. This prevents unsafe operations.

class Box<T>(val value: T)

fun main() {
    val strBox = Box("hi")
    // val anyBox: Box<Any> = strBox // would not compile
    println(strBox.value)
}

All lessons in this course

  1. Generic Functions and Classes
  2. Declaration-Site Variance
  3. Use-Site Variance
  4. Generic Constraints
← Back to Kotlin Academy