TExcelTAD
Home › Scala › Scala Givens & Using

Scala Givens & Using

Some values are needed "everywhere" but are tedious to pass by hand: a configuration, an execution context, a way to compare or format things. Scala 3's contextual abstractions solve this. You declare a given instance once, and methods that ask for a value with a using parameter receive it automatically from the context.

A first example

scala · try it yourself
case class Config(currency: String, decimals: Int)

def formatPrice(amount: Double)(using cfg: Config): String =
  s"%.${cfg.decimals}f %s".format(amount, cfg.currency)

def receipt(items: List[(String, Double)])(using Config): List[String] =
  items.map((name, price) => s"$name: ${formatPrice(price)}")

@main def run(): Unit =
  given Config = Config("EUR", 2)
  receipt(List("tea" -> 3.5, "cake" -> 4.25)).foreach(println)
  println(formatPrice(10)(using Config("JPY", 0)))
tea: 3.50 EUR
cake: 4.25 EUR
10 JPY
  • given Config = … puts a Config into the context.
  • (using cfg: Config) declares a context parameter. The compiler fills it with the given of that type.
  • receipt also has (using Config) — it does not even name it, it just passes it on to formatPrice implicitly.
  • You can still pass a value explicitly with (using …) at the call site.

How the compiler finds givens

For a using parameter of type T, the compiler looks for a given of type T:

  1. in the current scope (local definitions, enclosing blocks, imports), then
  2. in the implicit scope of T: the companion objects of T and of the types it is made of.

If none is found, compilation fails with a clear message: No given instance of type Config was found.

scala · try it yourself
case class Tax(rate: Double)

object Tax:
  given default: Tax = Tax(0.20)   // found automatically via the companion

def gross(net: Double)(using t: Tax): Double = net * (1 + t.rate)

@main def run(): Unit =
  println(gross(100))
  locally:
    given Tax = Tax(0.07)          // a local given wins over the companion's
    println(gross(100))
120.0
107.0

Putting a default given in the companion object is a common pattern: users get sensible behaviour with no imports, and can override it locally.

Summoning a given

summon[T] retrieves the given instance of T currently in scope:

scala · try it yourself
case class Greeting(text: String)

def greet(name: String)(using Greeting): String =
  s"${summon[Greeting].text}, $name!"

@main def run(): Unit =
  given Greeting = Greeting("Servus")
  println(greet("Lena"))
  println(summon[Greeting])
Servus, Lena!
Greeting(Servus)

Givens for Ordering

The standard library uses givens heavily. sorted, max and sortBy require an Ordering[T] given. For your own types you can provide one:

scala · try it yourself
case class Version(major: Int, minor: Int, patch: Int):
  override def toString = s"$major.$minor.$patch"

object Version:
  given Ordering[Version] = Ordering.by(v => (v.major, v.minor, v.patch))

@main def run(): Unit =
  val versions = List(Version(1, 10, 0), Version(1, 2, 3), Version(0, 9, 9), Version(1, 2, 10))
  println(versions.sorted)
  println(versions.max)
  println(versions.sorted(using summon[Ordering[Version]].reverse))
List(0.9.9, 1.2.3, 1.2.10, 1.10.0)
1.10.0
List(1.10.0, 1.2.10, 1.2.3, 0.9.9)

Without the given, versions.sorted would not compile: No given instance of type Ordering[Version].

Importing givens

Givens are not imported by a wildcard import x.*. You must ask for them explicitly with given:

scala
object Defaults:
  given Config = Config("USD", 2)
  def helper = 1

import Defaults.*        // imports helper, but NOT the given
import Defaults.given    // imports all givens
import Defaults.{given Config}  // imports only the given of type Config

This rule makes it obvious where contextual values come from.

given/using vs. Scala 2 implicits

Scala 3 Scala 2 equivalent
given x: T = … implicit val x: T = …
(using t: T) (implicit t: T)
summon[T] implicitly[T]
extension (x: A) implicit class Ops(x: A)
import a.given import a._ (imported implicits too)

Tip: Use givens for things that are genuinely contextual — configuration, type class instances, execution contexts. Ordinary business data should still be passed as normal parameters.

Test yourself

What does (using cfg: Config) declare?

  1. A default argument
  2. A context parameter filled automatically from a given Config
  3. A mutable variable
  4. An import

Does import Defaults.* import the givens defined in Defaults?

  1. Yes
  2. No, you need import Defaults.given
  3. Only in Scala 2
  4. Only if they are named

Which expression retrieves the given Ordering[Int] in scope?

  1. given[Ordering[Int]]
  2. summon[Ordering[Int]]
  3. using[Ordering[Int]]
  4. Ordering.get