Scala – Is Short-Circuit Evaluation a Consequence of Call-by-Name?

scala

If the boolean operators &&, || are implemented as infix methods, then isn't short-circuit evaluation just a consequence of being implemented using call-by-name semantics, since, for example, the && method wouldn't then evaluate the second arg in any case if the first is false.

I'm just wondering because they are generally treated as separate topics (e.g in the Scala intro course I'm taking – https://class.coursera.org/progfun-003/lecture/5 ) but short-circuit evaluation seems to just be a consequence of call-by-name.

Best Answer

Turns out Martin answers the exact question 15 minutes later on in the same video! Yes, short-circuit evaluation is implemented using call by-name args. Martin discusses just this and defines the and function as follows:

  def and(x:Boolean, y: => Boolean) {
    if (x) y else false
  }

Note that if the second arg y was not call-by-name, then and(false,<infinite loop expr>) would not terminate, whereas we would expect it to return false due to short-circuit eval.

Related Topic