1. 一元操作符
在Scala中,操作符其实就是方法,例如1 + 1等价于1.+(1),利用下划线我们可以定义自己的左置操作符,例如Scala中的负数就是用左置操作符实现的:-2和2.unary_-等价。来看另外一个例子
case class Complex(real: Double, imag: Double){
def unary_- : Complex = Complex(-real, -3*imag);
def unary_+ : Complex = Complex(2*real, 5*imag);
def -(other: Complex) = Complex(real - other.real, imag - other.imag);
}
object Test{
def main(args: Array[String]){
val c1 = Complex(1.1, 2.2);
val c2 = -c1;
val c3 = c1.unary_-;
val c4 = c1 - Complex( 0.5, 1.0 );// 等价于c1.-( Complex( 0.5, 1.0 ) )
val c5 = +c1;
println(c1);
println(c2);
println(c3);
println(c4);
println(c5);
}
}
// 运行结果
Complex(1.1,2.2)
Complex(-1.1,-6.6000000000000005)
Complex(-1.1,-6.6000000000000005)
Complex(0.6000000000000001,1.2000000000000002)
Complex(2.2,11.0)
上例中,方法名为unary_X, 这里的X就是我们想要使用的操作符。上面的X分别有"-"和"+"两种体现形式,后面重新定义了返回结果。