A given instance is a value or definition that Scala can select automatically for a context parameter. Define it with `given`, then let type-directed search supply it where a function requires it. section 10.5 section 10.9
The selection pattern has three parts:
- Declare a context parameter with a `using` parameter list, such as `using m: Monoid[B]`. section 10.5
- Define a matching instance, either named or anonymous: `given intAddition: Monoid[Int] with ...`. section 10.5
- Call the function without naming the instance; Scala searches lexical scope and relevant companion objects, or accepts an explicit `using` argument. section 10.5 section 10.9
- Use `summon[T]` to retrieve the selected instance of type `T`; compilation fails when no suitable instance exists. section 10.7.1 section 10.9
Folding without passing the monoid
Define `foldMap` as `def foldMap[A, B](as: List[A])(f: A => B)(using m: Monoid[B]): B`. A `given Monoid[Int]` supplies addition automatically, so `foldMap(List(1, 2, 3))(_ + 1)` needs no explicit monoid. A different behavior remains available through `using Monoid.booleanAnd` or another explicit instance. section 10.5 section 10.5
given intAddition: Monoid[Int] with def combine(a1: Int, a2: Int) = a1 + a2 val empty = 0
Inspect the minimal named given declaration that provides a `Monoid[Int]` for automatic selection. section 10.5
