O'Reilly logo

Scala Puzzlers by Nermin Šerifovic, Andrew Phillips

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Puzzler 23

Adaptive Reasoning

Scala supports two ways of passing arguments:

  1. By-value, which causes arguments to be evaluated before being passed to the method. This is the default.
  2. By-name, which causes arguments to be evaluated only when referenced inside the method.[1] By-name parameters are prefixed with the => symbol.

By-name parameters are useful in situations where you want to avoid evaluating an argument before a method call, especially if the evaluation is expensive. However, unlike lazy values, by-name parameters are evaluated each time they are referenced inside a method:

  def mod(a: => Double) = if (a >= 0) a else -a
    scala> mod({ println("evaluating"); -5.2 })
  evaluating
  evaluating
  res0: Double = 5.2

Another nice feature of Scala ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required