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
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 aConfiginto the context.(using cfg: Config)declares a context parameter. The compiler fills it with the given of that type.receiptalso has(using Config)— it does not even name it, it just passes it on toformatPriceimplicitly.- 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:
- in the current scope (local definitions, enclosing blocks, imports), then
- in the implicit scope of
T: the companion objects ofTand 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.
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:
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:
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:
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 ConfigThis 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?
- A default argument
- A context parameter filled automatically from a given
Config - A mutable variable
- An import
Does import Defaults.* import the givens defined in Defaults?
- Yes
- No, you need
import Defaults.given - Only in Scala 2
- Only if they are named
Which expression retrieves the given Ordering[Int] in scope?
given[Ordering[Int]]summon[Ordering[Int]]using[Ordering[Int]]Ordering.get