Scala:Operators
lastmod 2020-09-11created 2020-09-111 edits
About
Scala operators (e.g. +, -, *, ++, etc.) are methods.
For example, the following code
can be used as follows:
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:
- Unary operators start with
unary_. - Unary operators are limited to
unary_+,unary_-,unary_!, andunary_~.