Hassan
Hassan

Reputation: 396

Scala - Explicitly stating the short circuiting in defining && and || functions

In Scala source code for Boolean (here), it is said that the functions && and || can not be defined using the => syntax.

// Compiler won't build with these seemingly more accurate signatures
// def ||(x: => Boolean): Boolean
// def &&(x: => Boolean): Boolean

But I can't see any problem with those definitions!

Upvotes: 3

Views: 6136

Answers (2)

sjrd
sjrd

Reputation: 22085

These definitions are perfectly fine, from a language user point of view.

They are however difficult to deal with internally by the compiler. A by-name parameter is transformed into an anonymous function class extending scala.Function0[Boolean], which basically means that the condition

left() || right()

would be transformed to

left() || (new Function0[Boolean] {
  def apply(): Boolean = right()
})

Now, when emitting bytecode, the compiler would have a hard time emitting back something sensible with the efficiency intended by left() || right().

So, because this is a primitive operation in the language, working with the primitive type Boolean, the compiler allows itself to cheat, and ask that right() not be a by-name. It thus sees the original code, and can easily transform it to something like

if (left()) true else right()

which is the same thing as

left() || right()

So, basically, this is an implementation detail/shortcut.

Upvotes: 4

Allen Chou
Allen Chou

Reputation: 1237

The source code said it won't rather than can't, maybe you have wrongly interpreted it.

If you see line 56 of Boolean.scala, you will find some explaination for ||.

This method uses 'short-circuit' evaluation and behaves as if it was declared as def ||(x: => Boolean): Boolean. If a evaluates to true, true is returned without evaluating b.

same for && in the source code. To sum up, it can define like that but there is no need to because of short-circuiting.

Upvotes: 5

Related Questions