Course Content
Introduction to Scala
Introduction to Scala
Order of Operations
When combining multiple mathematical operations within one expression it is important to be aware of their order of execution. Luckily, Scala follows the order of these operations in mathematics.
1. Parentheses ()
Operations within parentheses ()
are performed first. This applies to nested parentheses, where the innermost set is evaluated first.
Let's take a look at an example:
Main
object Main { def main(args: Array[String]): Unit = { val result = (2 + 3) * 4 println(result) } }
In the expression (2 + 3) * 4
, the addition within the parentheses is performed before the multiplication, so the result is 20
.
2. Multiplication, Division, and Remainder
These operations have the next highest precedence after parentheses. They are evaluated from left to right. Let's take a look at an example to make things clear:
Main
object Main { def main(args: Array[String]): Unit = { val result = 2 + 3 * 4 % 5 / 2 println(result) } }
Since there are no parentheses in our expression multiplication, division, and remainder operations are executed first. The leftmost such operation is 3 * 4
, so it's evaluated first, the result is 12
. Next, we go to the right and evaluate 12 % 5
resulting in 2
. Afterward, we evaluate 2 / 2
resulting in 1
. Finally, the last operation is addition (2 + 1
), so the final result is 3
.
3. Addition and Subtraction
These operators have lower precedence than multiplication, division, and remainder. They are also evaluated from left to right.
Main
object Main { def main(args: Array[String]): Unit = { val result = 5 - 2 + 3 * 4 % 5 / 2 println(result) } }
As you can see, this example is similar to the previous one, so the subtraction and addition operations are performed last. Since we evaluate from left to right subtraction (5 - 2
) is calculated first resulting in 3
. Next, the addition is performed (3 + 1
) resulting in 4
since 3 * 4 % 5 / 2
is equal to 1
.
Thanks for your feedback!