Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท Functional Programming

Scala 3 Type Classes, Givens and Extension Methods

Learn Scala 3 contextual abstractions: given instances, using clauses, context bounds, extension methods and the type class pattern for flexible, reusable code.

Suppose you want one function that sorts anything: numbers, strings, your own Person class. It needs a way to compare two elements, but you cannot add a compare method to Int or String, and you may not own Person's source either. The Scala answer is the type class pattern: describe the capability in a small trait ("how to compare values of type A"), provide instances of it for the types you care about, and let the compiler pass the right instance automatically.

Scala 3 made this pattern a first-class feature with given, using and extension. You already use it daily: List(3, 1, 2).sorted works because an Ordering[Int] is available in scope.

Passing a capability explicitly

First, see the problem without any magic. Define the capability as a trait and pass it as an ordinary parameter:

SCALA
trait Show[A]:
  def show(a: A): String

val showInt: Show[Int] = n => s"Int($n)"
val showString: Show[String] = s => "\"" + s + "\""

def display[A](a: A, shower: Show[A]): String = shower.show(a)

println(display(42, showInt))        // Int(42)
println(display("hi", showString))   // "hi"

(Show has a single abstract method, so a lambda can create an instance.) This works but is noisy: every call must pass the instance. Givens let the compiler do that for you.

given and using

A given instance declares "this is the default Show[Int] in this scope". A using clause declares "this method needs a Show[A] and the compiler should look one up":

SCALA
given Show[Int] = n => s"Int($n)"
given Show[String] = s => "\"" + s + "\""

def display[A](a: A)(using shower: Show[A]): String = shower.show(a)

println(display(42))     // Int(42)
println(display("hi"))   // "hi"

display(42) needs a Show[Int]; the compiler searches the implicit scope (the current scope, imports, and the companion objects of the types involved) and finds the given. If it finds none you get a clear error: no given instance of type Show[Boolean] was found. If it finds two competing ones you get an ambiguity error, so there is no silent surprise.

Inside a method you can fetch the instance with summon[Show[A]].

The type class recipe

Define the trait trait Show[A] names the capability.
Write givens One instance per supported type.
Ask with using Methods require Show[A] in a using clause.
Compiler wires it It finds and passes the right instance.
1 / 2

Context bounds

When the only reason for a using parameter is to call summon, a context bound [A: Show] is shorter:

SCALA
def displayAll[A: Show](items: List[A]): String =
  items.map(summon[Show[A]].show).mkString(", ")

println(displayAll(List(1, 2, 3)))   // Int(1), Int(2), Int(3)

[A: Show] is sugar for "there is an unnamed using Show[A]".

Givens that build on givens

A given can itself take a using clause, so instances compose. A Show for lists follows from a Show for the elements:

SCALA
given [A](using inner: Show[A]): Show[List[A]] =
  xs => xs.map(inner.show).mkString("[", ", ", "]")

println(display(List(1, 2)))              // [Int(1), Int(2)]
println(display(List(List("a"), List("b"))))  // [["a"], ["b"]]

The compiler builds Show[List[List[String]]] by chaining three instances. This is called instance derivation and is the engine behind JSON libraries, ordering and equality of tuples, and more.

Extension methods

An extension adds a method to an existing type, so 5.isEven or "abc".show reads naturally without a wrapper:

SCALA
extension (n: Int)
  def isEven: Boolean = n % 2 == 0
  def squared: Int = n * n

println(10.isEven)    // true
println(7.squared)    // 49

extension [A](a: A)(using s: Show[A])
  def pretty: String = s.show(a)

println(42.pretty)         // Int(42)
println("x".pretty)        // "x"

Extensions can be generic and can require a given, as above. They are resolved at compile time, so they cost nothing at run time and never change the original class.

Ordering: a standard type class

The standard library's Ordering[A] is a type class. sorted, max, sortBy and TreeMap all use it:

SCALA
case class Person(name: String, age: Int)

given Ordering[Person] = Ordering.by(_.age)

val people = List(Person("Ann", 40), Person("Bo", 25), Person("Cy", 31))
println(people.sorted.map(_.name))   // List(Bo, Cy, Ann)
println(people.max.name)             // Ann

To sort a different way in one place, pass an ordering explicitly: people.sorted(using Ordering.by(_.name)) or simply people.sortBy(_.name). The explicit using argument syntax is how you override a given.

Where givens come from

The compiler looks in this order for a Show[Int]: givens in the local scope, givens imported with import Mod.given (a plain import Mod.* does not import givens in Scala 3), and the companion object of Show and of Int. Putting default instances in the type class's companion is a common design:

SCALA
object Show:
  given Show[Boolean] = b => if b then "yes" else "no"

Now display(true) works everywhere with no import, because Show's companion is always searched.

Scala 2 called these features implicit. Scala 3 still reads implicit code for compatibility, but new code should use given, using and extension, which are easier to read and harder to misuse.

The idea on the JVM

Java and Kotlin have no given, but the underlying idea, a separate object that describes how to handle a type, is familiar: Java's Comparator is a type class you pass explicitly. The examples below are Java and Kotlin, not Scala.

Java Java: Comparator as a type class (Java, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Kotlin Kotlin: extension functions and an explicit type class (Kotlin, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Common mistakes

  • Expecting import Mod.* to bring givens in. Use import Mod.given (or import Mod.{*, given}).
  • Defining two givens of the same type in the same scope, causing an ambiguity error.
  • Putting instances in an unrelated file where they are not found. Put defaults in the type class or data type's companion.
  • Using givens for plain configuration values. They are for capabilities; implicit-everything code is hard to follow.
  • Forgetting the name using at the call site when overriding explicitly: sorted(using ord).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does def f[A](a: A)(using s: Show[A]) tell the compiler?

    A using clause requests a contextual argument that the compiler resolves from the available given instances.
  2. 2. What is the short form of a using parameter that you only summon?

    [A: Show] means an anonymous using Show[A] parameter, retrievable with summon[Show[A]].
  3. 3. What does import Instances.* bring into scope in Scala 3?

    Wildcard imports skip givens. Use import Instances.given to import them.
  4. 4. Where should default instances of a type class usually live?

    Companion objects are part of the implicit scope, so instances there are found without imports.

Summary

  • A type class is a trait describing a capability for a type; instances are provided separately from the type.
  • given defines an instance, using (or a context bound) requests one, summon fetches one.
  • Givens can depend on other givens, which gives automatic derivation for containers.
  • extension adds methods to existing types; Ordering is the standard-library type class you use most.
  • Wildcard imports do not import givens; put defaults in companions.

Next: Futures and Promises