🔴 Scala Intermediate

What is variance in Scala generics?

Answer

Variance describes the subtyping relationship between generic types when the type parameter's subtype relationship changes. Covariant (+T): if A is a subtype of B, then C[A] is a subtype of C[B]. Example: class List[+T] — a List[Dog] can be used where a List[Animal] is expected. Safe for read-only (producer) types. Contravariant (-T): if A is a subtype of B, then C[B] is a subtype of C[A] — reversed. Example: trait Function1[-T, +R] — a function accepting Animal can be used where a function accepting Dog is expected. Safe for write-only (consumer) types. Invariant (no annotation): no subtyping relationship. Array[Dog] is NOT a subtype of Array[Animal] (arrays are mutable, so covariance would be unsound). The Liskov Substitution Principle guides variance decisions: produce covariance for output, contravariance for input.