Search code examples
scalashort-circuiting

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!


Solution

  • 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.