Explain the differences between variances in Scala (covariant, contravariant, invariant).
Instruction: Discuss each type of variance and provide examples where each would be used.
Context: This question aims to assess the candidate's understanding of Scala's type system, especially regarding how type parameters relate to their subtypes or supertypes.
Updated
Variance determines how a generic type's subtyping relates to its element type. If Dog <: Animal:
- Covariance,
Producer[+A], permitsProducer[Dog]whereProducer[Animal]is required. ImmutableList[+A]is a familiar example. - Contravariance,
Consumer[-A], permitsConsumer[Animal]whereConsumer[Dog]is required: a consumer able to handle every animal can handle a dog. - Invariance,
Cell[A], provides neither conversion merely from that element subtype relationship. A mutable cell both consumes and producesA, so blindly widening it would allow an incompatible write.
trait Animal { def name: String }
final case class Dog(name: String) extends Animal
trait Consumer[-A] { def accept(value: A): String }
final class Cell[A](var value: A)
@main def varianceExample(): Unit = {
val dogs: List[Dog] = List(Dog("Rex"))
val animals: List[Animal] = dogs
val animalConsumer: Consumer[Animal] = new Consumer[Animal] {
def accept(value: Animal): String = value.name
}
val dogConsumer: Consumer[Dog] = animalConsumer
assert(dogConsumer.accept(Dog("Rex")) == "Rex")
assert(animals.head.name == "Rex")
val dogCell: Cell[Dog] = new Cell(Dog("Rex"))
assert(dogCell.value.name == "Rex")
}
Assigning dogCell to Cell[Animal] is rejected. The compiler also checks whether uses of a type parameter are compatible with its declared variance; annotations are not unchecked permissions to cast. Variance rules
Do not describe the standard scala.math.Ordering[T] as Ordering[-T]: its type parameter is invariant. A custom consumer or the input side of a function is a clearer contravariant example. When adapting an ordering, use its documented operations such as on with an explicit projection, rather than assuming a variance conversion. Ordering API