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
