Operators Are Methods
Why does 5.0 max 8.5 work in Scala, with a word used like a plus sign? Because Scala has no special list of operators. An operator is an ordinary method with a short name, and that one idea explains both how operators work and in what order they run.
The rule
a op bisa.op(b); the first character decides precedence.
Writing 2 + 3 really calls a method named + on the number 2:
2 + 3 // the same as 2.+(3)
5.0 max 8.5 // the same as 5.0.max(8.5): 8.5
1 to 4 // the same as 1.to(4): the numbers 1, 2, 3, 4A method with one parameter can be written between its two operands like this, which is called infix style. Symbolic names such as + are almost always written that way; word names such as max can go either way.
When several operators meet, Scala ranks them by the first character of their name, from lowest to highest:
(any letter) lowest: max, min, to, until
|
^
&
= !
< >
:
+ -
* / %
(other symbols) highestSo 2 + 3 * 4 is 14, because * outranks +. And 3 max 2 + 5 is 7, because max begins with a letter and ranks lowest: it means 3 max (2 + 5). Assignment operators such as += sit below everything in the table.
Operators of equal rank run left to right: 10 - 4 - 3 is (10 - 4) - 3, which is 3. The one exception is names ending in a colon. They group to the right and belong to the value on their right, so 1 :: 2 :: Nil means 1 :: (2 :: Nil), a list built from the right.
When the order is not obvious to a reader, add parentheses. They cost nothing and remove the doubt.
The shortcut
To evaluate a mixed expression, rank by first character, then go left to right within a rank. Letters rank last, so word operators like max and to act on the finished arithmetic on each side of them.
Rank the operators
*and/share the top rank.maxstarts with a letter, so it goes last.
Drills
Answer fast — trust the rule.
What is 2 + 3 * 4?
What is 3 max 2 + 5?
How does 1 :: 2 :: Nil group?
What is 10 - 4 - 3?
Which call is exactly what 5.0 max 8.5 means?
Remember
- An operator is a method:
a op bmeansa.op(b). - Rank by first character (letters lowest,
* / %above+ -), then go left to right; names ending in:group to the right. - Trap: word operators like
maxrank below arithmetic, so add parentheses when in doubt.
