Groovy 에서 + 연산자를 사용하면 plus 라는 메소드가 동작한다.
Operator
|
Method
|
Operator
|
Method
|
+
|
a.plus(b)
|
a[b]
|
a.getAt(b)
|
-
|
a.minus(b)
|
a[b] = c
|
a.putAt(b, c)
|
*
|
a.multiply(b)
|
a in b
|
b.isCase(a)
|
/
|
a.div(b)
|
<<
|
a.leftShift(b)
|
%
|
a.mod(b)
|
>>
|
a.rightShift(b)
|
**
|
a.power(b)
|
>>>
|
a.rightShiftUnsigned(b)
|
|
|
a.or(b)
|
++
|
a.next()
|
&
|
a.and(b)
|
--
|
a.previous()
|
^
|
a.xor(b)
|
+a
|
a.positive()
|
as
|
a.asType(b)
|
-a
|
a.negative()
|
a()
|
a.call()
|
~a
|
a.bitwiseNegate()
|
왜냐하면 Groovy 의 모든 변수, 상수는 Class 이기 때문에 Class 간에 연산을 위해서는
Operator Overloading 이 필요하기 때문이다.
아래와 같이 기본형들에 대해서는 이미 Operator Overloading 이 되어 있어서 잘 동작하지만
def a = 1
def b = 2
println a + b
println a.plus(b)
def s1 = "Hello"
def s2 = ", World"
println s1 + s2
println s1.plus(s2)
|
3
3
Hello, World
Hello, World
|
이외 사용자 정의 클래스에서는 연산자를 사용하기 위해 위 표를 보고
그에 맞는 오버로딩을 위한 메서드를 정의해 주어야 제대로 동작하게 된다.
class Account {
BigDecimal balance
Account plus(Account other){
new Account(balance: this.balance + other.balance)
}
String toString(){
"Account Balance : $balance"
}
}
Account savings = new Account(balance:100.00)
Account checking = new Account(balance:500.00)
println savings + checking
|
Account Balance : 600.00
|
'Script > Groovy' 카테고리의 다른 글
08. RegExp (0) | 2020.01.21 |
---|---|
07. String (0) | 2020.01.21 |
05. DataType (0) | 2020.01.21 |
04. Basic Grammer (0) | 2020.01.21 |
03. IntelliJ IDE (0) | 2020.01.21 |