Context Functions
Context functions are function types that take a given value as their context. A context function type is written with a question mark and an arrow, such as Int ?=> Int.
A context function adds one to its given number
The function type Int ?=> Int asks for a given Int. Its body adds 1 to the summoned number.
@main def main(): Unit =
given Int = 5
val f: Int ?=> Int = summon[Int] + 1
println(f)A top-level context function doubles its given number
The function is written outside the program entry point. Inside the program, a given Int of 4 fills its context.
val doubleIt: Int ?=> Int = summon[Int] * 2
@main def main(): Unit =
given Int = 4
println(doubleIt)A context function can work with words
This function asks for a given word. Its body turns the summoned word into capitals.
val shout: String ?=> String = summon[String].toUpperCase
@main def main(): Unit =
given String = "hello"
println(shout)Example
val doubleIt: Int ?=> Int = summon[Int] * 2
val shout: String ?=> String = summon[String].toUpperCase
@main def main(): Unit =
given Int = 4
given String = "hello"
println(doubleIt)
println(shout)Key points
- Context: the given values in scope where the function is used.
- Context function type: a function type that asks for a given value instead of an ordinary argument.
- Summon inside: the body fetches its value with summon from the caller's context.
- No argument at the call: the given value in scope fills the context.
- Changed context: a different given in scope gives a different result from the same function.
In this example, one context function doubles a given number. The other turns a given word into capitals. Inside the program, a given number of 4 and a given word fill the contexts. The two prints show 8 and HELLO.
Note
Scala applies a context function on its own when a given of the needed type is in scope.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does val f: Int ?=> Int = summon[Int] + 1 do when used with a given Int of 5 in scope?