Skip to content
Search

Scala:Operators

lastmod 2020-09-11created 2020-09-111 edits

About

Scala operators (e.g. +, -, *, ++, etc.) are methods.

For example, the following code

1 + 2

can be used as follows:

1.+(2)

Methods of this kind are called infix operators.

Infix operators

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)
  }
}

It can be used as follows:

val a = new Matrix(2, 2, Seq(Seq(1,2), Seq(3,4)))
val b = new Matrix(2, 2, Seq(Seq(1,2), Seq(3,4)))

// could also be written a.+(b)
val sum = a + b
  • An infix operator can take only one argument.
  • The object before the operator is itself (self) for the operator applied to the object after the operator.
  • Any Scala method with one argument can be used as an infix operator.

Unary operators

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) 
  }   
}

It can be used as follows:

val a = new Matrix(2, 2, Seq(Seq(1,2), Seq(3,4)))
val negA = -a
  • Unary operators start with unary_.
  • Unary operators are limited to unary_+, unary_-, unary_!, and unary_~.

See also

Favorite site

author Zer0 sitemap