Difference between & and && in Scala?

14,273

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.

Share:
14,273
NeoWelkin
Author by

NeoWelkin

A learner,a helper, Technology enthusiast,programming sometimes to make web world beautiful and accessible.

Updated on June 04, 2022

Comments

  • NeoWelkin
    NeoWelkin almost 2 years

    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?