🎓 A1Learner
🔍
0 of 48 lessons completed

Scala Using Clauses

A using clause is a parameter list the compiler fills in from givens in scope. The caller may still pass the value by hand.

A using clause takes its value from a given

The method greet asks for a greeting with using. The given greeting fills it in.

given greeting: String = "Hello"
def greet(name: String)(using g: String): String = g + ", " + name
@main def main(): Unit =
  println(greet("Ana"))

A caller can pass a using argument by hand

The first call uses the given greeting. The second call passes Hi explicitly.

given greeting: String = "Hello"
def greet(name: String)(using g: String): String = g + ", " + name
@main def main(): Unit =
  println(greet("Ana"))
  println(greet("Bo")(using "Hi"))

One using clause can hold several parameters

The tag method asks for a prefix and a count. Two givens of different types fill them in.

given prefix: String = ">>"
given count: Int = 3
def tag(word: String)(using p: String, n: Int): String = p + word + "-" + n.toString
@main def main(): Unit =
  println(tag("note"))

Example

given greeting: String = "Hello"
given number: Int = 7
def format(word: String)(using g: String, n: Int): String = g + " " + word + " #" + n.toString
@main def main(): Unit =
  println(format("Ana"))
  println(format("Bo")(using "Hi", 9))

Key points

  • Using clause: a parameter list written with using that the compiler fills in.
  • Given supply: the compiler looks for a given of each using parameter type.
  • Explicit pass: a caller can still pass a using argument by hand with using at the call.
  • Multiple parameters: one using clause can hold several parameters of different types.
  • Default behaviour: when no explicit argument is given, the given value is used.

In this example, the givens are the greeting Hello and the number 7. The method format takes a word plus a using greeting and a using number. The first call fills in both givens and prints Hello Ana #7. The second call passes Hi and 9 explicitly and prints Hi Bo #9.

Note

an explicit using argument beats the given value for that one call only.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

Which call passes the greeting to greet explicitly instead of using the given value?