liveBook · Manning

Given instance

As explained in Functional Programming in Scala, Second Edition

The given keyword declares a Scala value or definition that can be selected as a contextual instance.

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

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains declarations, call-site search, companion-object lookup, explicit overrides, and recursive synthesis, but defers the full search algorithm.
Examples
Uses integer addition, string concatenation, nested map merging, Foldable implementations, and Console capabilities as concrete instances.
What it assumes
Assumes generic functions and typeclasses while teaching `using`, `given`, contextual search, and `summon` through Monoid examples.
What you can do after
Apply it via Scala 3 context parameters to define, discover, override, and recursively compose typeclass or capability instances.
How it connects
Connects given instances to context parameters, typeclasses, summon, companion objects, Foldable, Monoid, and Monad.

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.