1
1
---
2
2
layout : tour
3
- title : Operators
3
+ title : 运算符
4
4
5
5
discourse : false
6
6
@@ -13,3 +13,69 @@ language: zh-cn
13
13
next-page : by-name-parameters
14
14
previous-page : type-inference
15
15
---
16
+ 在Scala中,运算符即是方法。 任何具有单个参数的方法都可以用作 _ 中缀运算符_ 。 例如,可以使用点号调用 ` + ` :
17
+ ```
18
+ 10.+(1)
19
+ ```
20
+
21
+ 而中缀运算符则更易读:
22
+ ```
23
+ 10 + 1
24
+ ```
25
+
26
+ ## 定义和使用运算符
27
+ 你可以使用任何合法标识符作为运算符。 包括像 ` add ` 这样的名字或像 ` + ` 这样的符号。
28
+ ``` tut
29
+ case class Vec(val x: Double, val y: Double) {
30
+ def +(that: Vec) = new Vec(this.x + that.x, this.y + that.y)
31
+ }
32
+
33
+ val vector1 = Vec(1.0, 1.0)
34
+ val vector2 = Vec(2.0, 2.0)
35
+
36
+ val vector3 = vector1 + vector2
37
+ vector3.x // 3.0
38
+ vector3.y // 3.0
39
+ ```
40
+ 类 Vec 有一个方法 ` + ` ,我们用它来使 ` vector1 ` 和 ` vector2 ` 相加。 使用圆括号,你可以使用易读的语法来构建复杂表达式。 这是 ` MyBool ` 类的定义,其中有方法 ` and ` 和 ` or ` :
41
+
42
+ ``` tut
43
+ case class MyBool(x: Boolean) {
44
+ def and(that: MyBool): MyBool = if (x) that else this
45
+ def or(that: MyBool): MyBool = if (x) this else that
46
+ def negate: MyBool = MyBool(!x)
47
+ }
48
+ ```
49
+
50
+ 现在可以使用 ` and ` 和 ` or ` 作为中缀运算符:
51
+
52
+ ``` tut
53
+ def not(x: MyBool) = x.negate
54
+ def xor(x: MyBool, y: MyBool) = (x or y) and not(x and y)
55
+ ```
56
+
57
+ 这有助于让方法 ` xor ` 的定义更具可读性。
58
+
59
+ ## 优先级
60
+ 当一个表达式使用多个运算符时,将根据运算符的第一个字符来评估优先级:
61
+ ```
62
+ (characters not shown below)
63
+ * / %
64
+ + -
65
+ :
66
+ = !
67
+ < >
68
+ &
69
+ ^
70
+ |
71
+ (all letters)
72
+ ```
73
+ 这也适用于你自定义的方法。 例如,以下表达式:
74
+ ```
75
+ a + b ^? c ?^ d less a ==> b | c
76
+ ```
77
+ 等价于
78
+ ```
79
+ ((a + b) ^? (c ?^ d)) less ((a ==> b) | c)
80
+ ```
81
+ ` ?^ ` 具有最高优先级,因为它以字符 ` ? ` 开头。 ` + ` 具有第二高的优先级,然后依次是 ` ==> ` , ` ^? ` , ` | ` , 和 ` less ` 。
0 commit comments