Scala Type Classes
A type class describes a capability — "can be shown as text", "can be combined", "can be encoded as JSON" — that types can gain without changing their definitions or sharing a parent class. In Scala 3 a type class is simply a generic trait, its instances are givens, and extension methods make it pleasant to use. Libraries such as Cats, Circe and ZIO are built on this pattern.
The three parts of a type class
- A trait with a type parameter that declares the capability.
- Given instances for each type that supports it.
- Using clauses (or context bounds) in functions that need it.
// 1. the type class
trait Show[A]:
def show(a: A): String
// 2. instances
given Show[Int] with
def show(n: Int) = s"#$n"
given Show[Boolean] with
def show(b: Boolean) = if b then "yes" else "no"
case class Book(title: String, pages: Int)
given Show[Book] with
def show(b: Book) = s"\"${b.title}\" (${b.pages} p.)"
// 3. a function that requires the capability
def describe[A](label: String, a: A)(using s: Show[A]): String =
s"$label: ${s.show(a)}"
@main def run(): Unit =
println(describe("count", 42))
println(describe("done", true))
println(describe("book", Book("Dune", 412)))count: #42
done: yes
book: "Dune" (412 p.)
describe("x", 3.14) would not compile, because there is no Show[Double]. Errors are caught at compile time, not at run time.
Context bounds and extension syntax
Two features make type classes nicer to use:
- A context bound
[A: Show]is shorthand for[A](using Show[A]). - An extension method inside the trait lets you write
value.show.
trait Show[A]:
extension (a: A) def show: String
object Show:
given Show[Int] with
extension (n: Int) def show = n.toString
given Show[String] with
extension (s: String) def show = s"'$s'"
// derived instance: if we can show A, we can show List[A]
given [A: Show]: Show[List[A]] with
extension (xs: List[A]) def show = xs.map(_.show).mkString("[", ", ", "]")
def printAll[A: Show](items: A*): Unit =
items.foreach(i => println(i.show))
import Show.given // brings the instances (and their extension methods) into scope
@main def run(): Unit =
println(42.show)
println("hi".show)
println(List(1, 2, 3).show)
println(List(List("a"), List("b", "c")).show)
printAll(7, 8)42
'hi'
[1, 2, 3]
[['a'], ['b', 'c']]
7
8
import Show.given is needed here because 42.show is called on an Int: the compiler looks for extension methods in givens that are in scope, and Show's companion is not automatically searched for an Int receiver. (A using Show[A] parameter, by contrast, does search Show's companion — that is why printAll would work without the import.)
The instance for List[A] is built from the instance for A. The compiler assembles Show[List[List[String]]] automatically from the pieces.
A type class with laws: Monoid
A monoid is a type with an "empty" value and an associative way to combine two values. Once you have it, you can write one generic combineAll for numbers, strings, maps and anything else.
trait Monoid[A]:
def empty: A
extension (x: A) def |+|(y: A): A
given Monoid[Int] with
def empty = 0
extension (x: Int) def |+|(y: Int) = x + y
given Monoid[String] with
def empty = ""
extension (x: String) def |+|(y: String) = x + y
given [K, V: Monoid]: Monoid[Map[K, V]] with
def empty = Map.empty
extension (x: Map[K, V]) def |+|(y: Map[K, V]) =
y.foldLeft(x) { case (acc, (k, v)) =>
acc.updated(k, acc.get(k).fold(v)(_ |+| v))
}
def combineAll[A: Monoid](xs: List[A]): A =
xs.foldLeft(summon[Monoid[A]].empty)(_ |+| _)
@main def run(): Unit =
println(combineAll(List(1, 2, 3, 4)))
println(combineAll(List("type", "-", "class")))
val week1 = Map("apples" -> 3, "pears" -> 1)
val week2 = Map("apples" -> 2, "kiwis" -> 5)
println(combineAll(List(week1, week2)))10
type-class
Map(apples -> 5, pears -> 1, kiwis -> 5)
Deriving instances automatically
For common type classes the compiler can generate instances from the shape of a case class or enum. The built-in CanEqual (strict equality) supports this with derives:
import scala.language.strictEquality
case class UserId(value: Int) derives CanEqual
case class OrderId(value: Int) derives CanEqual
@main def run(): Unit =
println(UserId(1) == UserId(1))
// UserId(1) == OrderId(1) // does not compile under strictEquality
println("comparing different id types is now a compile error")true
comparing different id types is now a compile error
Libraries use the same derives mechanism, e.g. case class User(...) derives JsonCodec.
Type classes vs. inheritance
Inheritance (extends Showable) |
Type class (Show[A]) |
|
|---|---|---|
Works for types you don't own (Int, String) |
no | yes |
| Decided at | run time (dynamic dispatch) | compile time (given resolution) |
| Multiple implementations for one type | awkward | easy: different givens in different scopes |
Can combine instances (List[A] from A) |
no | yes |
Tip: Put a type class's standard instances in its companion object. The compiler searches there automatically when resolving
usingparameters, so callers need no imports; to use the extension syntax (42.show) on types you don't own, callers addimport Show.given.
Test yourself
In Scala 3, how is an instance of a type class usually provided?
- By extending the type class trait in the data type
- As a
giveninstance - With a global variable
- With reflection
What does the context bound in def f[A: Show](a: A) mean?
Amust extendShowftakes an extrausing Show[A]parameterAis a subtype ofStringShowis optional
What happens if you call a function requiring Show[Double] but no such given exists?
- It falls back to
toString - A runtime exception
- A compile error
- It prints nothing