Scala Given Instances
A given instance is a value the compiler finds by type when a method needs it. Callers do not pass it by hand.
A given value can be used by its name
The given greeting is a String with a name. Code can print it by that name, like any other value.
given greeting: String = "Hello, Scala"
@main def main(): Unit =
println(greeting)A given ordering compares values in reverse
The given ordering reverses Int order. Its compare method then reports 3 as smaller than 1.
given reverseOrd: Ordering[Int] = Ordering.Int.reverse
@main def main(): Unit =
println(reverseOrd.compare(3, 1))Two givens of different types can live side by side
The two givens have different types, so both may be in scope. Each is used by its own name.
given prefix: String = "Dr. "
given year: Int = 2026
@main def main(): Unit =
println(prefix + "Ada")
println(year)Example
given discount: Int = 5
given label: String = "Total: "
def finalPrice(price: Int, d: Int): Int = price - d
@main def main(): Unit =
println(label + finalPrice(20, discount))Key points
- Given instance: a value marked with given that the compiler can find by its type.
- Named access: a named given is an ordinary value too, so code can use its name directly.
- One per type: only one given of each type may be in scope at once.
- Scope: a given in a program is visible to the code written after it.
- Reading: a reader finds a given's value where the given is written.
In this example, the given discount is 5 and the given label is "Total: ". The method finalPrice takes a price and a discount as ordinary arguments. The call finalPrice(20, discount) gives 15, and the label in front of it prints "Total: 15".
Note
a given supplies a value silently, so a reader must look for the given to know where the value came from.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
A program has given greeting: String = "Hi". What does println(greeting) print?