官术网_书友最值得收藏!

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:

  1. (2 + (12 / 2)) - 1
  2. (2 + 6) - 1
  3. 8 - 1
  4. 7

It's based on operator precedence. That's in the following order:

Operator precedence

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. 1 + 2 + 9 * 4 - 1
  2. 1 + 2 + 36 - 1
  3. 3 + 36 - 1
  4. 39 - 1
  5. 38

This gives clarity of evaluation of expressions in Scala.

主站蜘蛛池模板: 宾川县| 栾城县| 湖州市| 双流县| 沐川县| 珲春市| 巩留县| 贺州市| 徐州市| 潼关县| 平昌县| 林西县| 惠水县| 青田县| 沙雅县| 青岛市| 太保市| 广水市| 龙泉市| 获嘉县| 拜城县| 土默特右旗| 梅州市| 融水| 视频| 常山县| 阿巴嘎旗| 永丰县| 洪湖市| 新蔡县| 招远市| 武夷山市| 苍山县| 南漳县| 临朐县| 桦川县| 西贡区| 邹平县| 林西县| 山东省| 黄大仙区|