定義自定義一元運算子
可以通過在運算子前新增 unary_
來定義一元運算子。一元運算子僅限於 unary_+
,unary_-
,unary_!
和 unary_~
:
class Matrix(rows: Int, cols: Int, val data: Seq[Seq[Int]]){
def +(that: Matrix) = {
val newData = for (r <- 0 until rows) yield
for (c <- 0 until cols) yield this.data(r)(c) + that.data(r)(c)
new Matrix(rows, cols, newData)
}
def unary_- = {
val newData = for (r <- 0 until rows) yield
for (c <- 0 until cols) yield this.data(r)(c) * -1
new Matrix(rows, cols, newData)
}
}
一元運算子可以如下使用:
val a = new Matrix(2, 2, Seq(Seq(1,2), Seq(3,4)))
val negA = -a
這應該與 parcimony 一起使用。使用不符合預期的定義過載一元運算子會導致程式碼混淆。