Unary operators can be defined by prepending the operator with unary_
. Unary operators are limited to unary_+
, unary_-
, unary_!
and 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)
}
}
The unary operator can be used as follows:
val a = new Matrix(2, 2, Seq(Seq(1,2), Seq(3,4)))
val negA = -a
This should be used with parcimony. Overloading a unary operator with a definition that is not what one would expect can lead to code confusion.