- Learning Scala Programming
- Vikash Sharma
- 256字
- 2021-06-30 19:07:52
Operator precedence
Operations such as 2 + 3 * 4 / 2 - 1 can give different results if there's no rule for evaluation of these. Hence we have some precedence-based rules for these. We're going to talk about it in this part:
scala> 2 + 3 * 4 / 2 - 1
res15: Int = 7
For reference purposes, we have the preceding expression. The evaluation gives back the result 7. How?
The expression (2 + ((3 * 4) / 2))) - 1 is evaluated in the following steps:
- (2 + (12 / 2)) - 1
- (2 + 6) - 1
- 8 - 1
- 7
It's based on operator precedence. That's in the following order:

As shown in the preceding figure, Scala operator expressions are evaluated based on the precedence shown. As per the figure, *, /, and % are of top priority, then comes + and -.
Other operators also follow the same precedence as shown. If operators of the same precedence level appear together, the operands are evaluated from left to right. It means that the expression 1 + 2 + 3 * 3 * 4 - 1 will result in 38:
scala> 1 + 2 + 3 * 3 * 4 - 1
res16: Int = 38
The expression (1 + 2) + ((3 * 3) * 4) - 1 will be evaluated in the following steps:
- 1 + 2 + 9 * 4 - 1
- 1 + 2 + 36 - 1
- 3 + 36 - 1
- 39 - 1
- 38
This gives clarity of evaluation of expressions in Scala.
- Learning LibGDX Game Development(Second Edition)
- Python編程自學手冊
- 名師講壇:Java微服務架構實戰(SpringBoot+SpringCloud+Docker+RabbitMQ)
- Reactive Android Programming
- 網站構建技術
- Mastering Drupal 8 Views
- 飛槳PaddlePaddle深度學習實戰
- Go語言精進之路:從新手到高手的編程思想、方法和技巧(1)
- 區塊鏈技術與應用
- Unity 2018 Augmented Reality Projects
- Python應用開發技術
- C++面向對象程序設計
- 詩意的邊緣
- LiveCode Mobile Development Hotshot
- Learning Unity Physics