Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between & and && in Scala? [duplicate]

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?

like image 935
NeoWelkin Avatar asked Dec 11 '22 10:12

NeoWelkin


1 Answers

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.

like image 74
Yuval Itzchakov Avatar answered Dec 26 '22 14:12

Yuval Itzchakov