liveBook · Manning

Context parameter

As explained in Functional Programming in Scala, Second Edition

A context parameter is a parameter whose argument can be supplied automatically by contextual or given-instance search.

A context parameter is a parameter whose argument Scala supplies through given-instance search. Writing a parameter list with using lets a generic function such as foldMap depend on a Monoid[B] without requiring callers to name that monoid. section 10.5

Define candidate values with given. At a call site, Scala searches the lexical scope and relevant companion objects for a matching instance. The inferred result type guides the search: foldMap(strings)(_.length) requests Monoid[Int] and can find intAddition automatically. section 10.5 section 10.9

Context parameters support several complementary forms of composition:

  • Keep multiple alternatives as ordinary values when no single canonical choice is appropriate, then pass one explicitly with using. section 10.5
  • Use summon to retrieve the matching given, or let instance search recurse through context parameters to assemble nested structures such as Map[String, Map[String, Int]]. section 10.7.1
  • Treat the mechanism as type-driven composition: the function requests a capability, while the compiler supplies an instance appropriate to the requested type. section 10.9

Implicit monoid selection

A fold can be declared as def foldMap[A, B](as: List[A])(f: A => B)(using m: Monoid[B]): B. With a given Monoid[Int] in scope, foldMap(List(1, 2, 3))(_ > 0) selects a Boolean monoid instead; an explicit (using Monoid.booleanAnd) or (using Monoid.booleanOr) chooses the desired behavior when alternatives exist. section 10.5

def foldMap[A, B](as: List[A])(f: A => B)(using m: Monoid[B]): B =
  as.foldRight(m.empty)((a, acc) => m.combine(f(a), acc))

Shows the core foldMap signature with its using parameter and the point where the selected monoid supplies empty and combine. section 10.5

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains declarations, given-instance search, companion-object lookup, explicit using, and recursive synthesis through nested requirements.
Examples
Uses foldMap, canonical integer and string monoids, Boolean alternatives, and nested Map monoid synthesis.
What it assumes
Assumes familiarity with generic functions and typeclasses while illustrating the mechanism through Monoid and foldMap examples.
What you can do after
Apply it via Scala given and using syntax, retrieve instances with summon, and select alternatives explicitly when inference needs direction.
How it connects
Connects context parameters to typeclasses, monoids, given instances, summon, and implicit parameters.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.