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
- Generic Functions and Classes
- Declaration-Site Variance
- Use-Site Variance
- Generic Constraints