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?
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 first
s value and then exit the conditional.
You can use bitwise AND (&
) to perform bitwise operations on integers, which is similar to most programming languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With