Difference between & and && in Scala?

NeoWelkin picture NeoWelkin · Jul 13, 2017 · Viewed 11.3k times · Source

I am trying to figure out the difference between & and && in Scala. I got this after searching

& <-- verifies both operands

&& <-- stops evaluating if the first operand evaluates to false since the result will be false

Can somebody explain the same with example as am not clear, what verifying both operands means here. Are we talking about just Booleans?

Answer

Yuval Itzchakov picture Yuval Itzchakov · Jul 13, 2017

Both are logical AND operators in Scala. The first form, &, will evaluate both operands values, for example:

val first = false
val second = true

if (first & second) println("Hello!")

Will evaluate both first and second before exiting the if condition, although we know that once a false appears in a logical AND, that entire expression will already yield false.

This is what && is for, and what it does is short-circuit the evaluation, meaning you only ever evaluate firsts value and then exit the conditional.

You can use bitwise AND (&) to perform bitwise operations on integers, which is similar to most programming languages.