Operators Precedence in Scala
An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Which operator is performed first in an expression with more than one operators with different precedence is determined by operator precedence.
For example, 10 + 20 * 30 is calculated as 10 + (20 * 30) and not as (10 + 20) * 30.
when two operators of the same precedence appear in expression associativity is used. Associativity can be Right to Left or Left to Right. For example ‘*’ and ‘/’ have the same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is worked as “(100 / 10) * 10”.
In below table operators with the highest precedence appear at the top of the table and operators with the lowest precedence appear at the bottom.
Left to Right
|! ~||Unary||Right to Left|
|* / %||Multiplicative||Left to Right|
|+ –||Additive||Left to Right|
|>> >>> <<||Shift||Left to Right|
|< <= > >=||Relational||Left to Right|
|== !=||Relational is equal to/is not equal to||Left to Right|
|== !=||Equality||Left to Right|
|&||Bitwise AND||Left to Right|
|^||Bitwise exclusive OR||Left to Right|
||||Bitwise inclusive OR||Left to Right|
|&&||Logical AND||Left to Right|
|| |||Logical OR||Left to Right|
|= += -= *= /= %= >>= <<= &= ^= |=||Assignment||Right to left|
|Comma (separate expressions)||Left to Right|
Below is the example of operator Precedence.
Value of a + b * c / d is : 50
In above example e = a + b * c / d; here, e is assigned 50, not 120 because operator * has a higher precedence than / than +, so it first gets multiplied with 10 * 15, then divide by 5 and then add into 20.