-1

I noticed something today. Scala has the usual OR ||, but also the |.

My first thought was that the | was a strict OR. So true | true, will evaluate to false. But,

val x = true
x: Boolean = true
val y = true
y: Boolean = true
x || y
res4: Boolean = true
x | y
res5: Boolean = true

What is the | operator for? Is it just an alias?

1 Answer 1

9

As in Java, the single & and | operators do the same thing as their usual versions but without short-circuiting.

As an example, consider the expression true || isNice(). The method will never be called because true || x is always true and the compiler (and runtime) knows that. If you insist on all parts of a boolean expression to be evaluated, you have to use & or |.

Edit: For completeness, Scala also uses the | for alternative patterns in pattern matching. This is copied from the language reference:

8.1.11 Pattern Alternatives Syntax: Pattern ::= Pattern1 { ‘|’ Pattern1 }

A pattern alternative p1 | ... | pn consists of a number of alternative patterns pi . All alternative patterns are type checked with the expected type of the pattern. They may no bind variables other than wildcards. The alternative pattern matches a value v if at least one its alternatives matches v.

3

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.