views:

164

answers:

3
+1  Q: 

&& and || in Scala

Hi,

since normal operators like +, ::, -> and so on are all methods which can be overloaded and stuff I was wondering if || and && are methods as well. This could theoretically work if this were methods in of the boolean object. But if they are, why is something like

if (foo == bar && buz == fol)

possible? If the compiler reads from right to left this would invoke && on bar instead of (foo == bar)

+7  A: 

Because method starts with = has a higher precedence than method starts with &.

So (foo == bar && buz == fol) will become something like the following:

val tmp1: Boolean = (foo == bar)
val tmp2: Boolean = (buz  == fol)

tmp1 && tmp2
Brian Hsu
+8  A: 

6.12.3 Infix Operations An infix operator can be an arbitrary identifier. Infix operators have precedence and associativity defined as follows:

The precedence of an infix operator is determined by the operator’s first character. Characters are listed below in increasing order of precedence, with characters on the same line having the same precedence.

  • (all letters)
  • |
  • ^
  • &
  • < >
  • = !
  • :
  • + -
  • * / %
  • (all other special characters)

That is, operators starting with a letter have lowest precedence, followed by operators starting with ‘|’, etc.

There’s one exception to this rule, which concerns assignment operators(§6.12.4). The precedence of an assigment operator is the same as the one of simple assignment (=). That is, it is lower than the precedence of any other operator.

It follows with an explanation of associativity, and how it all combines in a expression with multiple operators. The Scala Reference makes good reading.

Daniel