Variance and bounds
Two questions follow a type parameter. The first is how a container of a subtype relates to a container of its supertype, which the declaration answers with a variance annotation. The second is what the type parameter itself must be able to do, which a bound answers. Both are written where the type is declared, so every use is checked against them.
Covariance and contravariance
Source[+A] only ever produces an A, so a source of dogs is a source of animals: the annotation + is covariance. Sink[-A] only ever consumes an A, so a sink of animals is a sink of dogs: the annotation - is contravariance. Without an annotation a type is invariant, and neither assignment compiles:
variance.scala
trait Animal:
def name: String
class Dog extends Animal:
def name: String = "dog"
trait Source[+A]:
def get: A
trait Sink[-A]:
def put(value: A): Unit
@main def variance(): Unit =
val dogs: Source[Dog] = new Source[Dog]:
def get: Dog = new Dog
val animals: Source[Animal] = dogs
println(animals.get.name)
val animalSink: Sink[Animal] = new Sink[Animal]:
def put(value: Animal): Unit = println(s"animal ${value.name}")
val dogSink: Sink[Dog] = animalSink
dogSink.put(new Dog)
scala-cli run --server=false variance.scala
dog
animal dog
The second half reads backwards at first. A sink of animals can be used where a sink of dogs is expected, because whatever it is given will be an animal. The compiler accepts only the annotations that are safe: +A may appear in a result position and -A in a parameter position, and putting one in the wrong place is a compile error. List[+A] is covariant for that reason, and Array[A] cannot be.
Upper and lower bounds
A <: Named says that whatever the caller passes must have a name, so the body may call it. A >: Dog says the opposite: the caller may pass any supertype of Dog, which is what a method that puts a dog into a collection of something wider needs:
bounds.scala
trait Named:
def name: String
case class Dog(name: String) extends Named
class Puppy(name: String) extends Dog(name)
def label[A <: Named](value: A): String =
value.name.toUpperCase
def herd[A >: Dog](adult: A, puppy: Dog): List[A] =
List(adult, puppy)
@main def bounds(): Unit =
println(label(Dog("rex")))
println(label(Puppy("bit")))
println(herd(Dog("rex"), Dog("bit")).map(_.name))
println(herd[Named](Dog("rex"), Dog("bit")).map(_.name))
scala-cli run --server=false bounds.scala
REX
BIT
List(rex, bit)
List(rex, bit)
label is called with a Dog and with a Puppy, and the upper bound is what lets the body read name from either. herd returns a list of A: with no type argument it is a List[Dog], and herd[Named](...) widens it to a list of the base type, which is the lower bound at work. A bound is a promise to the body of the method, checked at the call site.
Why an Array is invariant
A list of strings can be used as a list of anything, and an array of strings cannot. The compiler refuses the assignment, and the reason is that an array can be written to:
invariant.scala
@main def invariant(): Unit =
val strings = Array("a", "b")
val objects: Array[AnyRef] = strings
println(objects.length)
mkdir -p out
scalac -color:never -d out invariant.scala 2>&1; echo "exit status: $?"
-- [E007] Type Mismatch Error: invariant.scala:3:31 ----------------------------
3 | val objects: Array[AnyRef] = strings
| ^^^^^^^
| Found: (strings : Array[String])
| Required: Array[AnyRef]
|
| longer explanation available when compiling with `-explain`
1 error found
exit status: 1
If the assignment were allowed, the array of strings could be reached through the wider name and an integer could be stored in it, and the failure would appear at the read, far from the mistake. The compiler refuses at the assignment instead. A List has no such hole because nothing can write to it, and that is the whole connection between mutability and variance.
Related
- Generics: the type parameter both annotations are written on.
- Union and intersection types: the other two ways two types are combined.
- Arrays and ranges: the mutable sequence an array of this lesson is.
- Java: the same rule, written as ? extends T and ? super T at each use.
Article author: Arthur Isaev