Scala : “运算符” 重载
运算符带了双引号,这是因为从技术上来说,Scala 并没有所谓的“运算符”,在这里是指重载符号,如+ ,+- 等等。
在 Scala 中,事实上这些是方法的名字。但是由于 Scala 并不需要点来分隔对象引用和方法名,因而看起来像是运算符。调用 ref1+ref2 其实与 ref1.+(ref2)是等同的,调用的其实是 ref1 的+()方法。
举例如下:
class Complex(val real: Int, val imaginary: Int) {
def +(operand: Complex) : Complex = {
new Complex(real + operand.real, imaginary + operand.imaginary)
}
override def toString() : String = {
real + (if (imaginary < 0) "" else "+") + imaginary + "i"
}
}
val c1 = new Complex(1, 2)
val c2 = new Complex(2, -3)
val sum = c1 + c2
println("(" + c1 + ") + (" + c2 + ") = " + sum)
运行结果:
(1+2i) + (2-3i) = 3-1i
再次强调,Scala 并不存在运算符,所以没有定义运算符优先级,但是同时又定义了方法的优先级。方法的第一个字符用来决定它们的优先级,如果两个同等优先级的字符在同个表达式中出现,那左边的优先。
下面的列出了字符从低到高的优先级:
all letters | ^ & <> =! : +- */% all other special characters
下面的例子中定义了加法和乘法:
class Complex(val real: Int, val imaginary: Int) {
def +(operand: Complex) : Complex = {
println("Calling +")
new Complex(real + operand.real, imaginary + operand.imaginary)
}
def *(operand: Complex) : Complex = {
println("Calling *")
new Complex(real * operand.real - imaginary * operand.imaginary,
real * operand.imaginary + imaginary * operand.real)
}
override def toString() : String = {
real + (if (imaginary < 0) "" else "+") + imaginary + "i"
}
}
val c1 = new Complex(1, 4)
val c2 = new Complex(2, -3)
val c3 = new Complex(2, 2)
println(c1 + c2 * c3)
从运算结果可以看到*的优先级高于+ :
Calling * Calling + 11+2i
Related posts:
评论