TExcelTAD
Home › Scala › Scala Generics & Variance

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:

scala · try it yourself
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

scala · try it yourself
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
scala · try it yourself
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)
scala · try it yourself
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 cats
Tom, Kit
crate holds Rex
treating Mia

Why mutable containers must be invariant

If Array were covariant, this would compile and then crash:

scala
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].

scala · try it yourself
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?

  1. A must be a supertype of Animal
  2. A must be Animal or a subtype of it
  3. A must have a given Animal
  4. A is unrelated to Animal

List is declared as List[+A]. What does that allow?

  1. Passing a List[Cat] where a List[Animal] is expected
  2. Adding elements in place
  3. Passing a List[Animal] where a List[Cat] is expected
  4. Nothing special

Why is Array[A] invariant?

  1. For performance only
  2. Because arrays are mutable; covariance would let you store the wrong type
  3. Because Java requires it
  4. It is actually covariant