Scala:Operators
About
스칼라 연산자 (예: +
, -
, *
, ++
등) 는 메서드 이다.
예를 들어 다음의 코드는
다음과 같이 사용할 수 있다:
이러한 종류의 메소드를 삽입 연산자 (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)
}
}
다음과 같이 사용할 수 있다:
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
- 삽입 연산자는 하나의 인수 만 가질 수 있다.
- 연산자 앞에있는 객체는 연산자 뒤에 객체에 대한 자신(
self
)의 연산자 이다. - 하나의 인수를 가진 스칼라 메서드는 중위 연산자로 사용할 수 있습니다.
단항 연산자
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)
}
}
다음과 같이 사용할 수 있다:
- 단항 연산자는
unary_
로 시작한다. - 단항 연산자는
unary_+
,unary_-
,unary_!
,unary_~
로 제한된다.