By-name parameters

A parameter of type => T takes an expression and evaluates it at every use, not at the call. The argument is a block of code without a function value, which is what a logging call, an assertion and a short-circuit need: the work happens only when the body asks for it.

A parameter of type => T

The body of twice prints its argument twice, and the argument next() is a call with a side effect. With a by-name parameter the call happens twice, which the counter proves:

byname.scala

def twice(message: => String): Unit = println(message) println(message) @main def byName(): Unit = var count = 0 def next(): String = count += 1 s"call $count" twice(next()) println(count)

scala-cli run --server=false byname.scala

call 1
call 2
2

A parameter of type String would have evaluated next() once, at the call, and both lines would say call 1. The by-name form moves the evaluation into the method, so the count reaches two.

When the argument is evaluated

An argument that the body never uses is never evaluated. choose takes two by-name strings and returns one of them; the other one is not computed, which the flag is there to show:

lazyargs.scala

def choose(flag: Boolean, first: => String, second: => String): String = if flag then first else second def log(enabled: Boolean)(message: => String): Unit = if enabled then println(message) @main def lazyArgs(): Unit = println(choose(true, "yes", "no")) var evaluated = false def expensive(): String = evaluated = true "value" println(choose(false, expensive(), "cheap")) println(evaluated) log(false)("never printed") log(true)("printed")

scala-cli run --server=false lazyargs.scala

yes
cheap
false
printed

choose(false, expensive(), "cheap") returns "cheap" and the flag stays false: the first argument was never touched. That is the difference between a by-name parameter and a function value — a function value is created when it is passed, and its body runs when it is called.

A helper that short-circuits

log is the shape a library uses: the first list is the condition, the second is the message, and the message costs nothing when the condition is false. A logging call that builds its string in the argument — a concatenation, an interpolator, a query — pays for it only on the calls that print. assert and require of the standard library are written the same way.

A by-name parameter is evaluated at every reference, so a body that uses it twice evaluates it twice. A parameter that must be evaluated once and kept is a lazy val inside the method, not a by-name parameter.

Related

Автор статьи: Arthur Isaev

Изображение баннера