Explain how 'By-name Parameters' work in Scala.

Instruction: Describe the concept of 'By-name Parameters' and their use cases in Scala.

Context: This question assesses deferred and repeated argument evaluation, the distinction from memoization, and appropriate use cases for by-name parameters.

Updated

A by-name parameter, written value: => A, receives an expression that is evaluated whenever the parameter is used. An unused parameter is not evaluated. By-name does not mean evaluate once and cache the result. By-name parameters

def twice(value: => Int): Int = value + value
def once(value: => Int): Int = {
  lazy val saved = value
  saved + saved
}
def when(enabled: Boolean)(message: => String): Option[String] =
  if (enabled) Some(message) else None

@main def byNameExample(): Unit = {
  var calls = 0
  def next(): Int = { calls += 1; calls }
  assert(twice(next()) == 3 && calls == 2)
  calls = 0
  assert(once(next()) == 2 && calls == 1)
  assert(when(false) { calls += 1; "expensive message" }.isEmpty)
  assert(calls == 1)
}

The local lazy val in once caches its successfully initialized value; that behavior comes from the lazy binding. A by-value parameter would evaluate the argument once before entering the method, even if the method never used it.

By-name parameters suit conditional logging, assertions and control abstractions. They can avoid unnecessary work, but repeated use can also repeat expensive work, side effects or exceptions. Document the evaluation contract and decide deliberately whether repeated evaluation or cached evaluation is intended.

Related Questions