What does 'Call-by-Name' parameter passing mean in Scala?

Instruction: Explain the concept of call-by-name parameter passing and its benefits in Scala.

Context: This question assesses deferred and repeated parameter evaluation, control abstractions, and the distinction between by-name evaluation and memoization.

Updated

A by-name parameter has the form argument: => A. The caller supplies an expression; the callee evaluates that expression each time it uses the parameter. An unused parameter is never evaluated. This enables control abstractions that decide when and how often work happens.

def whileDo(condition: => Boolean)(body: => Unit): Unit = {
  while (condition) { body }
}
@main def controlExample(): Unit = {
  var value = 0
  var conditionChecks = 0
  whileDo({ conditionChecks += 1; value < 3 }) {
    value += 1
  }
  assert(value == 3 && conditionChecks == 4)
  whileDo(false) { throw new IllegalStateException("unused") }
}

The condition sees the current value on every test, and the body runs three times. With by-value parameters, those argument expressions would run before entering the method; the body would not represent repeatable deferred work. By-name parameters

By-name evaluation does not cache a result. If evaluate-once behavior is intended, store the expression in a local lazy val and use that binding. Avoid assuming deferred work is cheaper: repeated use may repeat expensive computation, I/O or side effects. Exceptions propagate when the expression is evaluated. The caller must supply a condition and body that terminate when termination is required; this helper does not impose a timeout or execution limit.

Related Questions