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.
Previous
What are type bounds in Scala generics?
Next
How does error handling work with Try in Scala?
More Scala Questions
View all →- Intermediate What is the type class pattern in Scala?
- Intermediate What is Akka and what is the actor model?
- Intermediate What is Apache Spark and how does Scala relate to it?
- Intermediate What is Scala's approach to concurrency with Futures and Promises?
- Intermediate What are Scala's monads and how do they work?