定义自定义一元运算符

可以通过在运算符前添加 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 一起使用。使用不符合预期的定义重载一元运算符会导致代码混淆。