Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 424
Travis Parks Avatar asked Jul 31 '14 19:07

Travis Parks


People also ask

What is Boolean in Scala?

Boolean (equivalent to Java's boolean primitive type) is a subtype of scala. AnyVal. Instances of Boolean are not represented by an object in the underlying runtime system. There is an implicit conversion from scala.

Is Boolean immutable in Scala?

Boolean is immutable like Strings, you can change the value of it and allocate new mem allocation, but the first reference remains on the memory allocation who has the false value.

Can strings be Booleans?

To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".


1 Answers

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

like image 82
Lee Avatar answered Oct 24 '22 08:10

Lee