Skip to content

Latest commit

 

History

History
49 lines (33 loc) · 1.67 KB

ca-context-bounds.md

File metadata and controls

49 lines (33 loc) · 1.67 KB
title type description num previous-page next-page
Context Bounds
section
This page demonstrates Context Bounds in Scala 3.
62
types-type-classes
ca-given-imports

{% comment %}

  • TODO: define "context parameter"
  • TODO: define "synthesized" and "synthesized arguments" {% endcomment %}

In many situations the name of a context parameter doesn’t have to be mentioned explicitly, since it’s only used by the compiler 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[A](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[A](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.