Skip to content
LumenaryAcademy
Practice 65 min

Traits, generics and type classes

Mixins and their linearisation, type parameters and variance, and Scala 3's contextual abstractions, given, using and extension methods.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Three ways to write code once

Good programs avoid saying the same thing twice. When you notice that two pieces of code differ only in a detail, you want to write the common part once and supply the detail separately. Scala offers three complementary tools for this, and this lesson is about all three.

Traits capture behaviour that many classes share. A trait is like an interface that can also contain code, and a class can mix in several of them, assembling its behaviour from parts.

Generics capture code that works the same way for many types. List[A] is one definition that serves as a list of integers, a list of strings and a list of your own case classes, with the compiler checking that you never mix them up.

Type classes capture behaviour that you want to add to types after the fact, including types you did not write, such as Int or List. "Can be turned into JSON", "can be compared for ordering", "can be added together" are typical type classes. Scala 3 gives them first-class syntax with given and using, and they are central to modern Scala libraries.

You have already used all three without noticing: Seq is a trait, List[A] is generic, and sorted quietly asked for an Ordering, a type class instance. Now you will learn to write them.

Worked examplesH

Traits and mixins

Definition— Trait

A trait declares members that classes can inherit. It may contain abstract members (declared, not defined), concrete methods and fields. A class extends one class or trait and may mix in more traits, separated by commas. Traits cannot be instantiated on their own, but in Scala 3 they can take parameters.

scala
trait Greeter:
  def name: String
  def greet(): String = s"Hello, I am $name"

trait Polite extends Greeter:
  override def greet(): String = super.greet() + ", pleased to meet you"

trait Loud extends Greeter:
  override def greet(): String = super.greet().toUpperCase + "!"

class Robot(val name: String) extends Greeter
class Butler(val name: String) extends Polite
class Herald(val name: String) extends Polite, Loud
class Crier(val name: String) extends Loud, Polite

@main def traits(): Unit =
  val all: List[Greeter] = List(Robot("Unit 7"), Butler("Kofi"), Herald("Lena"), Crier("Bo"))
  for g <- all do println(g.greet())
text
Hello, I am Unit 7
Hello, I am Kofi, pleased to meet you
HELLO, I AM LENA, PLEASED TO MEET YOU!
HELLO, I AM BO!, pleased to meet you

Greeter has an abstract member, name, that each class provides (here with a val constructor parameter), and a concrete greet. Polite and Loud each modify greet and pass the call on with super.greet().

The interesting part is what super means when several traits are mixed in. Scala arranges a class and its traits in a single line called the linearisation: roughly, the class first, then its traits from right to left, then their parents. A super call goes to the next trait in that line. For Herald (extends Polite, Loud) the line is Herald, Loud, Polite, Greeter: Loud runs first, asks Polite, which asks Greeter; so the polite sentence is built first and then shouted. For Crier the order is reversed, and only the greeting itself is shouted. This lets traits act as stackable modifications, layers you add to a behaviour. Real code uses the pattern for things like adding logging, caching or retries around an operation.

Traits are also the building block of the sealed hierarchies from lesson 4, and the way Scala programmers describe a component's interface: a trait declares what a service can do, and one or more classes implement it, including a fake implementation for tests.

Worked examplesH

Generics and variance

Definition— Type parameter

A type parameter, written in square brackets, lets a class or method work for any type: case class Box[A](value: A) and def firstOr[A](xs: List[A], default: A): A. The compiler infers type arguments at most call sites. An upper bound A <: Animal requires A to be a subtype of Animal; a lower bound B >: A requires B to be a supertype of A.

scala
sealed trait Animal:
  def name: String
case class Dog(name: String) extends Animal
case class Cat(name: String) extends Animal

case class Box[A](value: A):
  def map[B](f: A => B): Box[B] = Box(f(value))

def firstOr[A](xs: List[A], default: A): A = xs.headOption.getOrElse(default)

def names(animals: List[Animal]): String = animals.map(_.name).mkString(", ")

enum Stack[+A]:
  case Empty
  case Push(top: A, rest: Stack[A])

  def push[B >: A](b: B): Stack[B] = Push(b, this)
  def toList: List[A] = this match
    case Empty          => Nil
    case Push(top, rest) => top :: rest.toList

@main def generics(): Unit =
  println(Box(21).map(_ * 2))
  println(Box("scala").map(_.length))
  println(firstOr(List("x", "y"), "none"))
  println(firstOr(List.empty[Int], -1))

  val dogs: List[Dog] = List(Dog("Laika"), Dog("Hachiko"))
  println(names(dogs))

  val describe: Animal => String = a => s"an animal called ${a.name}"
  val describeDog: Dog => String = describe
  println(describeDog(Dog("Rex")))

  val dogStack: Stack[Dog] = Stack.Empty.push(Dog("Rex"))
  val animalStack: Stack[Animal] = dogStack.push(Cat("Mitsi"))
  println(animalStack.toList)
text
Box(42)
Box(5)
x
-1
Laika, Hachiko
an animal called Rex
List(Cat(Mitsi), Dog(Rex))

Box and firstOr are generic in the simplest way. The rest of the program is about a subtler question: if a Dog is an Animal, is a List[Dog] a List[Animal]? That relationship between a generic type and its type argument is called variance.

Definition— Variance

A generic type F[A] is covariant (written F[+A]) if F[Dog] is a subtype of F[Animal] whenever Dog is a subtype of Animal; contravariant (F[-A]) if the relationship is reversed; and invariant (plain F[A]) if there is no relationship.

  • Immutable containers are covariant. List is declared List[+A], so names(dogs) accepts a list of dogs where a list of animals is expected. That is safe because nobody can put a cat into an existing list of dogs; the list can only be read.
  • Function parameters are contravariant. A function that can describe any animal can certainly describe a dog, so an Animal => String may be used as a Dog => String. Function types are declared Function1[-A, +B]: contravariant in what they consume, covariant in what they produce.
  • Mutable containers must be invariant. Imagine a class Cage[A](var occupant: A). If a Cage[Dog] could be treated as a Cage[Animal], you could put a Cat in it, and someone holding the original Cage[Dog] would take out a cat. The compiler refuses the conversion:
text
-- [E007] Type Mismatch Error: main.scala:9:33
9 |  val animalCage: Cage[Animal] = dogCage
  |                                 ^^^^^^^
  |                                 Found:    (dogCage : Cage[Dog])
  |                                 Required: Cage[Animal]

This is why Scala's Array is invariant, while Java's arrays are covariant and can throw an ArrayStoreException at run time for exactly this reason.

The Stack[+A] enum shows the standard trick for adding to a covariant structure. push cannot take an A, because a covariant A may not appear as a method parameter; instead it takes any supertype B >: A and returns a Stack[B]. Pushing a Cat onto a Stack[Dog] therefore produces a Stack[Animal]. List's own :: is declared the same way.

Worked examplesH

Type classes with given and using

Suppose you want to turn values into JSON text. You could add a toJson method to every class, but you cannot add methods to Int, String or List, and you would mix serialisation code into every data type. A type class solves both problems: a generic trait describes the ability, and separate instances provide it for each type.

Definition— Type class, given and using

A type class is a generic trait such as JsonEncoder[A]. A given instance (given JsonEncoder[Int]: ...) is the canonical implementation for one type, registered with the compiler. A using clause ((using encoder: JsonEncoder[A])) is a parameter the compiler fills in automatically with the given instance of the right type. A context bound [A: JsonEncoder] is shorthand for such a parameter, and summon[JsonEncoder[A]] retrieves it.

scala
trait JsonEncoder[A]:
  def encode(a: A): String

def toJson[A](a: A)(using encoder: JsonEncoder[A]): String = encoder.encode(a)

object JsonEncoder:
  given JsonEncoder[String]:
    def encode(s: String) = "\"" + s.replace("\"", "\\\"") + "\""
  given JsonEncoder[Int]:
    def encode(n: Int) = n.toString
  given JsonEncoder[Boolean]:
    def encode(b: Boolean) = b.toString
  given [A: JsonEncoder] => JsonEncoder[List[A]]:
    def encode(xs: List[A]) = xs.map(toJson).mkString("[", ",", "]")
  given [A: JsonEncoder] => JsonEncoder[Option[A]]:
    def encode(o: Option[A]) = o.map(toJson).getOrElse("null")

case class Station(name: String, elevation: Int, open: Boolean, lines: List[String], note: Option[String])

object Station:
  given JsonEncoder[Station]:
    def encode(s: Station) =
      val fields = List(
        "name" -> toJson(s.name),
        "elevation" -> toJson(s.elevation),
        "open" -> toJson(s.open),
        "lines" -> toJson(s.lines),
        "note" -> toJson(s.note)
      )
      fields.map((k, v) => s"${toJson(k)}:$v").mkString("{", ",", "}")

def describe[A: JsonEncoder](label: String, a: A): String =
  s"$label = ${summon[JsonEncoder[A]].encode(a)}"

@main def typeClasses(): Unit =
  println(toJson(42))
  println(toJson(List(true, false)))
  println(toJson(List(Some(1), None, Some(3))))
  val s = Station("Cusco", 3399, true, List("A", "B"), None)
  println(toJson(s))
  println(describe("terminals", List("Lagos \"Ikeja\"", "Abuja")))
text
42
[true,false]
[1,null,3]
{"name":"Cusco","elevation":3399,"open":true,"lines":["A","B"],"note":null}
terminals = ["Lagos \"Ikeja\"","Abuja"]

Follow what the compiler does for toJson(List(Some(1), None, Some(3))). It needs a JsonEncoder[List[Option[Int]]]. The given for lists can produce one if it gets a JsonEncoder[Option[Int]]; the given for options can produce that if it gets a JsonEncoder[Int]; and that one exists. The compiler assembles the chain at compile time, with no reflection and no run-time lookup. The given [A: JsonEncoder] => JsonEncoder[List[A]] syntax reads as "given an encoder for A, here is an encoder for List[A]". If no instance can be found, compilation fails with a clear message, for example for a Double:

text
No given instance of type JsonEncoder[Double] was found for parameter encoder of method toJson

Where does the compiler look? In the current scope and imports, and also in the companion objects of the types involved: of JsonEncoder itself and of Station. That is why the instances live in those objects; users get them without importing anything. Libraries such as circe, zio-json and upickle work on exactly this principle (and can generate instances like Station's automatically, with derives).

The standard library is full of type classes. sorted, max and min take a using Ordering[A]; sum takes a Numeric[A]. Provide an Ordering for your own type and those methods work on it:

scala
case class Version(major: Int, minor: Int, patch: Int):
  override def toString = s"$major.$minor.$patch"

object Version:
  def parse(text: String): Version =
    val Array(a, b, c) = text.split('.').map(_.toInt)
    Version(a, b, c)
  given Ordering[Version] = Ordering.by(v => (v.major, v.minor, v.patch))

extension (v: Version)
  def bumpMinor: Version = v.copy(minor = v.minor + 1, patch = 0)

extension (s: String)
  def words: List[String] = s.split("\\s+").toList.filter(_.nonEmpty)
  def isPalindrome: Boolean =
    val letters = s.toLowerCase.filter(_.isLetter)
    letters == letters.reverse

opaque type Celsius = Double
object Celsius:
  def apply(degrees: Double): Celsius = degrees
  extension (c: Celsius) def toFahrenheit: Double = c * 9 / 5 + 32

@main def extensions(): Unit =
  val versions = List("1.10.0", "1.2.3", "1.9.12", "0.9.0").map(Version.parse)
  println(versions.sorted)
  println(versions.max)
  println(versions.max.bumpMinor)
  println(List("1.2.3", "1.10.0").sorted)

  println("  the quick   brown fox ".words)
  println("Was it a car or a cat I saw?".isPalindrome)

  val bodyTemp = Celsius(37.0)
  println(bodyTemp.toFahrenheit)
text
List(0.9.0, 1.2.3, 1.9.12, 1.10.0)
1.10.0
1.11.0
List(1.10.0, 1.2.3)
List(the, quick, brown, fox)
true
98.6

Ordering.by builds an ordering from a key; tuples are compared field by field, so versions sort numerically, and 1.10.0 correctly comes after 1.9.12. Compare the last sorted line, where the same text sorted as strings puts 1.10.0 first.

Extension methods and opaque types

An extension method adds a method to an existing type without touching it: after extension (s: String) def words ..., every string has .words. The compiler rewrites "...".words into a call to the extension; there is no wrapper object at run time. Extension methods are how you give a type-class-based library a pleasant syntax, and they are also simply a tidy way to organise helper functions.

An opaque type alias creates a new type that is represented by an existing one. Inside its defining scope, Celsius is a Double; everywhere else it is a distinct type, so you cannot pass a raw Double, or a Fahrenheit, where a Celsius is required. It costs nothing at run time. Opaque types are the idiomatic way to stop identifiers, units and money amounts from being mixed up.

ExplanationH

Choosing between inheritance, type classes and plain functions

With three tools that all avoid repetition, how do you choose? Professional Scala code tends to follow a few rules of thumb.

Use a trait with subclasses when you have a closed set of variants of one concept (a sealed trait or enum, matched exhaustively) or when you describe a component's interface that several implementations will provide, such as a PaymentGateway trait with a real implementation and a fake for tests. Keep inheritance hierarchies shallow; deep chains of classes overriding each other are as hard to follow in Scala as anywhere else.

Use a type class when the behaviour is an ability that many unrelated types may have, especially types you do not control: encoding to JSON, comparing, hashing, displaying, combining. A type class keeps that code out of your data types and lets you add the ability to Int or List as easily as to your own case classes. It also lets one type have the ability in a context-dependent way: the same Version could have one Ordering in your code and you could pass a different one explicitly, for one call, with versions.sorted(using customOrdering).

Use a plain function when neither applies. Not everything needs an abstraction. A top-level function taking a case class is often the clearest code you can write, and it is easy to turn into an extension method later if the dot syntax reads better.

Two warnings from experience. First, avoid defining givens for very general types such as String or Int in shared scope (a given Int = 42 is legal and confusing). Givens should be for type-class instances, whose type tells you what they are for. Second, if you find yourself fighting the compiler about variance, step back: making a type invariant is always safe, and covariance is worth adding only for immutable containers that people will genuinely use polymorphically.

History & global context

From implicits to givens

Scala 2 had one keyword, implicit, that did several jobs: implicit parameters (now using), implicit values (now given), implicit classes (now extension methods) and implicit conversions, which silently convert a value of one type into another. The mechanism was powerful, and libraries such as Cats built a whole style of programming on it, but the single keyword made code hard to read: when you saw implicit, you had to work out which of the four meanings was intended, and implicit conversions in particular could make code do surprising things.

Scala 3 separated the jobs and gave each its own syntax. Implicit conversions still exist, as given instances of scala.Conversion, but the compiler warns wherever one is applied unless that file imports scala.language.implicitConversions, which nudges people away from them. The current form of given syntax, with given [A: Ord] => Ord[List[A]], arrived in Scala 3.6; older code writes given listOrd[A](using Ord[A]): Ord[List[A]] with ..., which still compiles. You will see all of these forms in real code bases, including Scala 2's implicit, which Scala 3 still accepts for compatibility.

Common misconceptionsH

Common misconceptions

Misconception

"Traits are mixed in left to right, so the leftmost one runs first." super calls follow the linearisation, in which the rightmost trait comes first. In extends Polite, Loud, Loud.greet runs first and calls Polite.greet through super.

Misconception

"If Dog is an Animal, then any container of dogs is a container of animals." Only if the container is covariant, which is safe only when it is read-only. Mutable containers are invariant, and the compiler checks your variance annotations to make sure they are sound.

Misconception

"Givens are global variables in disguise." A given is resolved at compile time, by type, from a well-defined set of places (local scope, imports, and companion objects of the types involved). It should be the single canonical instance for its type, such as the ordering of versions, not a way to pass configuration around invisibly. When there is more than one sensible choice, pass the value explicitly.

Misconception

"Extension methods change the class." They are ordinary functions that the compiler lets you call with dot syntax. They cannot access private members, and they apply only where they are in scope.

Exercises

Exercises

1. Traits, generics and type classes

CoreComputational

What does println(C().tag) print?

trait Base:
  def tag: String = "base"
trait A extends Base:
  override def tag: String = "A(" + super.tag + ")"
trait B extends Base:
  override def tag: String = "B(" + super.tag + ")"
class C extends A, B

2. Traits, generics and type classes

CoreHuman

Dog is a subtype of Animal. Which assignments compile? Choose all that apply.

Choose all that apply

3. Traits, generics and type classes

CoreComputational

What does println(tell(List(1, 2, 3, 4))) print?

trait Describe[A]:
  def describe(a: A): String
given Describe[Int]:
  def describe(n: Int) = if n % 2 == 0 then "even" else "odd"
given [A: Describe] => Describe[List[A]]:
  def describe(xs: List[A]) = xs.map(summon[Describe[A]].describe).mkString("/")
def tell[A: Describe](a: A): String = summon[Describe[A]].describe(a)

4. Traits, generics and type classes

Warm-upComputational

What does println(3.times("ab")) print?

extension (n: Int)
  def times(s: String): String = s * n

5. Traits, generics and type classes

Warm-upComputational

With extension (n: Int) def isDivisibleBy(d: Int): Boolean = n % d == 0, what is (1 to 20).count(_.isDivisibleBy(4))?

6. Traits, generics and type classes

CoreHuman

You define case class Money(cents: Long) and want List[Money] to work with sorted everywhere, with no import needed. Where should given Ordering[Money] = Ordering.by(_.cents) go?

Choose one

7. Traits, generics and type classes

StretchHuman

What does opaque type UserId = Long give you that type UserId = Long does not?

Choose one

Further reading and resources