Scala Type Classes
A type class is a trait that describes one ability for many types. Each type gets its own given instance of that trait.
One method works for any type with an instance
Show describes turning a value into text. The given Show for Int lets display show 42.
trait Show[T]:
def show(v: T): String
given Show[Int] with
def show(v: Int): String = v.toString
def display[T](v: T)(using s: Show[T]): String = s.show(v)
@main def main(): Unit =
println(display(42))Each type can show itself in its own way
The given Show for String wraps the value in quotes. Display then prints the quoted word.
trait Show[T]:
def show(v: T): String
given Show[String] with
def show(v: String): String = "\"" + v + "\""
def display[T](v: T)(using s: Show[T]): String = s.show(v)
@main def main(): Unit =
println(display("hi"))A custom type gains the ability with its own instance
Point is a new type with x and y. Its given Show prints both fields.
trait Show[T]:
def show(v: T): String
case class Point(x: Int, y: Int)
given Show[Point] with
def show(v: Point): String = "x=" + v.x.toString + ", y=" + v.y.toString
def display[T](v: T)(using s: Show[T]): String = s.show(v)
@main def main(): Unit =
println(display(Point(1, 2)))Example
trait Show[T]:
def show(v: T): String
given Show[Int] with
def show(v: Int): String = v.toString
given Show[String] with
def show(v: String): String = "\"" + v + "\""
given Show[Boolean] with
def show(v: Boolean): String = v.toString
def display[T](v: T)(using s: Show[T]): String = s.show(v)
@main def main(): Unit =
println(display(42))
println(display("hi"))
println(display(true))Key points
- Type class: a trait that describes one ability that many types can share.
- Instance: a given instance of the trait supplies the ability for one type.
- Using method: a method with a using parameter for the trait works for any type with an instance.
- New types: a new type gains the ability by adding its own given instance.
- No change: adding an instance for a new type does not change the method.
In this example, Show has one given instance for Int, one for String, and one for Boolean. The method display takes any value plus a using Show for its type. Each call picks the matching instance, so the three lines print 42, the quoted word hi, and true.
Note
a type class keeps the ability separate from the types that use it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
Display works for Int and String. What is needed for display(true) to compile?