🐦 Kotlin
Advanced
What is covariance (out) in Kotlin generics?
Answer
Covariance, declared with the out keyword, means a generic class is a producer of values of that type — it can only return (produce) values of that type, never accept (consume) them. This allows assignment from a subtype to a supertype reference: a List<Dog> can be assigned to List<Animal> because List is declared out T. interface Producer<out T> { fun produce(): T }. Covariance preserves the subtype relationship: if Dog is a subtype of Animal, then Producer<Dog> is a subtype of Producer<Animal>. This is why Kotlin's immutable collections are covariant.
Previous
What is lazy thread safety mode in Kotlin?
Next
What is contravariance (in) in Kotlin generics?