- 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.
- .NET之美:.NET關鍵技術深入解析
- Microsoft Exchange Server PowerShell Cookbook(Third Edition)
- Spring 5.0 By Example
- Drupal 8 Blueprints
- Building a Home Security System with Raspberry Pi
- 零基礎學Scratch少兒編程:小學課本中的Scratch創意編程
- 精通軟件性能測試與LoadRunner實戰(第2版)
- Instant QlikView 11 Application Development
- 深度學習:算法入門與Keras編程實踐
- RESTful Java Web Services(Second Edition)
- Kotlin進階實戰
- 用Go語言自制編譯器
- C/C++語言程序開發參考手冊
- Expert Angular
- Magento 2 -Build World-Class online stores