TL ; DR:
When we string operations together, Scala must know which one to do first. This is called operator precedence.
*and/are performed before+and-:
println(1 + 2 * 3) // Prints 7
println(6 - 4 / 2) // Prints 4
println(5 * 4 - 2 / 2) // Prints 19
We can add () to force an operation to be performed first:
println((1 + 2) * 3) // Prints 9
println((6 - 4) / 2) // Prints 1
println(5 * (4 - 2) / 2) // Prints 5
Full lesson:
When we string operations together, Scala must know which one to do first. This is called operator precedence.
This is the hierarchy from highest precedence to lowest precedence:
- Parentheses are always respected
- Exponentiation (raise to a power)
- Multiplication, Division and Remainder
- Addition and Subtraction
- Left to right
First example:
println(1 + 2 * 3) // Output: 7
Multiplication is executed before addition, so:
1 + 2 * 3 = 1 + 6 = 7
Second example:
println((1 + 2) * 3) // Output: 9
What's inside parentheses is executed before multiplication, so:
(1 + 2) * 3 = 3 * 3 = 9
Third example:
println(6 / 4 * 3 + 5) // Output: 9.5
Multiplication and division come before addition. Also, multiplication and division have the same priorty so they are executed from left to right:
6 / 4 * 3 + 5 = 1.5 * 3 + 5 = 4.5 + 5 = 9.5
Forth example:
println(6 / ((4 + 2) / 3)) // Output: 3
Computer sees parentheses so it looks at it like this:
6 / ((4 + 2) / 3) = 6 / x, where x = (4 + 2) / 3
I have to compute x first. Parantheses are executed before division:
(4 + 2) / 3 = 6 / 3 = 2
I can replace x with 2:
6 / ((4 + 2) / 3) = 6 / 2 = 3
Assignment
Follow the Coding Tutorial and let's practice with operator precedence!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.