在 Scala 中,運算子是方法。任何具有單一參數的方法都可以用作中綴運算子。例如,+
可以用點號表示法呼叫
10.+(1)
不過,將其讀作中綴運算子比較容易閱讀
10 + 1
定義和使用運算子
您可以使用任何合法的識別碼作為運算子。這包括像 add
這樣的名稱或像 +
這樣的符號。
case class Vec(x: Double, y: Double) {
def +(that: Vec) = Vec(this.x + that.x, this.y + that.y)
}
val vector1 = Vec(1.0, 1.0)
val vector2 = Vec(2.0, 2.0)
val vector3 = vector1 + vector2
vector3.x // 3.0
vector3.y // 3.0
case class Vec(x: Double, y: Double):
def +(that: Vec) = Vec(this.x + that.x, this.y + that.y)
val vector1 = Vec(1.0, 1.0)
val vector2 = Vec(2.0, 2.0)
val vector3 = vector1 + vector2
vector3.x // 3.0
vector3.y // 3.0
類別 Vec 有方法 +
,我們用它來新增 vector1
和 vector2
。使用括號,您可以使用可讀語法建立複雜的表達式。以下是類別 MyBool
的定義,其中包含方法 and
和 or
case class MyBool(x: Boolean) {
def and(that: MyBool): MyBool = if (x) that else this
def or(that: MyBool): MyBool = if (x) this else that
def negate: MyBool = MyBool(!x)
}
case class MyBool(x: Boolean):
def and(that: MyBool): MyBool = if x then that else this
def or(that: MyBool): MyBool = if x then this else that
def negate: MyBool = MyBool(!x)
現在可以使用 and
和 or
作為中綴運算子
def not(x: MyBool) = x.negate
def xor(x: MyBool, y: MyBool) = (x or y) and not(x and y)
這有助於使 xor
的定義更具可讀性。
優先順序
當一個表達式使用多個運算子時,運算子會根據第一個字元的優先順序進行評估
(characters not shown below)
* / %
+ -
:
< >
= !
&
^
|
(all letters, $, _)
這適用於您定義的函式。例如,下列表達式
a + b ^? c ?^ d less a ==> b | c
等於
((a + b) ^? (c ?^ d)) less ((a ==> b) | c)
?^
具有最高的優先順序,因為它以字元 ?
開頭。 +
具有第二高的優先順序,其次是 ==>
、^?
、|
和 less
。