scalabooleanoperators

Scala - Booleans - & vs. &&, | vs. ||


I just noticed that in Scala Boolean supports both & and &&. Is there a difference between these two operators? The Scala docs use the exact same description for both of them, so I wasn't sure.

Compares two Boolean expressions and returns true if both of them evaluate to true.


Solution

  • & and | are strict while && and || are short-circuiting:

    false && (throw new Exception()) => false
    false & (throw new Exception()) => ex
    
    true || (throw new Exception()) => true
    true | (throw new Exception()) => ex
    

    The full documentation for & and | have a note explaining this behaviour:

    This method evaluates both a and b, even if the result is already determined after evaluating a.