Work in Progress

Scala 3 has not been released, yet. We are still in the process of writing the documentation for Scala 3. You can help us to improve the documentation.

Are you searching for the Scala 2 documentation?

Scala 3 — Book

Context Bounds

Language

In many situations the name of a context parameter doesn’t have to be mentioned explicitly, since it’s only used in synthesized arguments for other context parameters. In that case you don’t have to define a parameter name, and can just provide the parameter type.

Background

For example, this maximum method takes a context parameter of type Ord, only to pass it on as an argument to max:

def maximum[T](xs: List[A])(using ord: Ord[A]): A =
  xs.reduceLeft(max(ord))

In that code the parameter name ord isn’t actually required; it can be passed on as an inferred argument to max, so you just state that maximum uses the type Ord[A] without giving it a name:

def maximum[T](xs: List[A])(using Ord[A]): A =
  xs.reduceLeft(max)

Context bounds

Given that background, a context bound is a shorthand syntax for expressing the pattern of, “a context parameter that depends on a type parameter.”

Using a context bound, the maximum method can be written like this:

def maximum[A: Ord](xs: List[A]): A = xs.reduceLeft(max)

A bound like : Ord on a type parameter A of a method or class indicates a context parameter with Ord[A].

For more information about context bounds, see the “What are context bounds?” section of the Scala FAQ.

Contributors to this page: