Scala Generics & Variance
Generics let you write classes and methods that work with any type while staying type-safe. List[A], Option[A] and Map[K, V] are all generic. Variance answers a subtle follow-up question: if a Cat is an Animal, is a List[Cat] a List[Animal]?
Generic methods
Type parameters go in square brackets before the value parameters:
def firstOr[A](xs: List[A], default: A): A =
xs.headOption.getOrElse(default)
def swap[A, B](pair: (A, B)): (B, A) = (pair._2, pair._1)
def repeat[T](value: T, times: Int): List[T] = List.fill(times)(value)
@main def run(): Unit =
println(firstOr(List(3, 4), 0))
println(firstOr(List.empty[String], "none"))
println(swap(("key", 99)))
println(repeat('*', 5).mkString)3
none
(99,key)
*****
The compiler infers A from the arguments, so you rarely write firstOr[Int](…) yourself.
Generic classes
class Box[A](val content: A):
def map[B](f: A => B): Box[B] = Box(f(content))
override def toString = s"Box($content)"
case class Pair[A](left: A, right: A):
def swap: Pair[A] = Pair(right, left)
@main def run(): Unit =
val b = Box(21)
println(b.map(_ * 2))
println(b.map(n => s"#$n"))
println(Pair("x", "y").swap)Box(42)
Box(#21)
Pair(y,x)
Type bounds
Sometimes "any type" is too broad. Bounds restrict type parameters:
| Bound | Meaning |
|---|---|
A <: Animal |
upper bound: A must be Animal or a subtype |
A >: Cat |
lower bound: A must be Cat or a supertype |
A: Ordering |
context bound: a given Ordering[A] must exist |
trait Animal:
def name: String
def sound: String
case class Cat(name: String) extends Animal:
def sound = "meow"
case class Dog(name: String) extends Animal:
def sound = "woof"
def loudest[A <: Animal](animals: List[A]): A = animals.maxBy(_.sound.length)
def largest[A: Ordering](xs: List[A]): A = xs.max
@main def run(): Unit =
val cats = List(Cat("Tom"), Cat("Kit"))
val c: Cat = loudest(cats) // the result is still typed as Cat
println(c)
println(largest(List(3, 9, 4)))
println(largest(List("pear", "apple")))Cat(Tom)
9
pear
With the upper bound, loudest can use sound, and returns the precise type Cat rather than just Animal.
Variance
Given Cat <: Animal, how does Container[Cat] relate to Container[Animal]? You decide with an annotation on the type parameter:
| Declaration | Name | Container[Cat] is a Container[Animal]? |
Typical for |
|---|---|---|---|
Container[A] |
invariant | no | mutable containers (Array, ArrayBuffer) |
Container[+A] |
covariant | yes | immutable producers (List, Option, Vector) |
Container[-A] |
contravariant | no — the reverse: Container[Animal] is a Container[Cat] |
consumers (A => B input, printers, comparators) |
trait Animal:
def name: String
case class Cat(name: String) extends Animal
case class Dog(name: String) extends Animal
// covariant: a producer of A
case class Crate[+A](item: A)
// contravariant: a consumer of A
trait Vet[-A]:
def treat(a: A): String
val generalVet: Vet[Animal] = new Vet[Animal]:
def treat(a: Animal) = s"treating ${a.name}"
def petAll(animals: List[Animal]): String = animals.map(_.name).mkString(", ")
def openCrate(c: Crate[Animal]): String = s"crate holds ${c.item.name}"
def bookCatVet(v: Vet[Cat]): String = v.treat(Cat("Mia"))
@main def run(): Unit =
val cats: List[Cat] = List(Cat("Tom"), Cat("Kit"))
println(petAll(cats)) // List is covariant
println(openCrate(Crate(Dog("Rex"))))
println(bookCatVet(generalVet)) // a Vet[Animal] can treat catsTom, Kit
crate holds Rex
treating Mia
Why mutable containers must be invariant
If Array were covariant, this would compile and then crash:
val cats: Array[Cat] = Array(Cat("Tom"))
val animals: Array[Animal] = cats // not allowed — Array is invariant
animals(0) = Dog("Rex") // would put a Dog into an Array[Cat]!Scala rejects the second line at compile time. Immutable List can safely be covariant because you can never put something into an existing list — Dog("Rex") :: cats simply creates a new List[Animal].
case class Cat(name: String)
case class Dog(name: String)
@main def run(): Unit =
val cats = List(Cat("Tom"))
val mixed = Dog("Rex") :: cats // the element type widens automatically
println(mixed)List(Dog(Rex), Cat(Tom))
Here the type of mixed is inferred as List[Cat | Dog] — a union of both element types.
Tip: A simple rule of thumb: types you only read from can be
+A; types you only write to can be-A; types you read and write must stay invariant.
Test yourself
What does A <: Animal mean in a type parameter list?
Amust be a supertype ofAnimalAmust beAnimalor a subtype of itAmust have a givenAnimalAis unrelated toAnimal
List is declared as List[+A]. What does that allow?
- Passing a
List[Cat]where aList[Animal]is expected - Adding elements in place
- Passing a
List[Animal]where aList[Cat]is expected - Nothing special
Why is Array[A] invariant?
- For performance only
- Because arrays are mutable; covariance would let you store the wrong type
- Because Java requires it
- It is actually covariant