Groovy also has the function of operator overloading. In fact, operators also call specific methods in the class. Using operators looks more concise and easy to understand.
Simple overloading for a subtraction
class Money{
def number
def minus(o){
if(o instanceof Money){
number-=o.number
}else if(o instanceof Number){
number-=o
}
this
}
@Override
public String toString() {
return "Money{" +
"number=" + number +
'}';
}
}
def m=new Money(number: 100)
def b=new Money(number: 50)
println m-b
println m-30
result:
Money{number=50}
Money{number=20}
The table of operator overloading is attached below, you can check it yourself, the original blog address https://www.cnblogs.com/rollenholt/archive/2013/10/02/3349047.html
The following table describes the methods to which operators in groovy map:
Operator |
Method |
a + b |
a.plus(b) |
a – b |
a.minus(b) |
a * b |
a.multiply(b) |
a ** b |
a.power(b) |
a / b |
a.div(b) |
a % b |
a.mod(b) |
a | b |
a.or(b) |
a & b |
a.and(b) |
a ^ b |
a.xor(b) |
a++ or ++a |
a.next() |
a– or –a |
a.previous() |
a[b] |
a.getAt(b) |
a[b] = c |
a.putAt(b, c) |
a << b |
a.leftShift(b) |
a >> b |
a.rightShift(b) |
switch(a) { case(b) : } |
b.isCase(a) |
~a |
a.bitwiseNegate() |
-a |
a.negative() |
+a |
a.positive() |
In addition, it should be noted that all the following operators will not throw java.lang.NullPointerException when they encounter null
Operator |
Method |
a == b |
a.equals(b) or a.compareTo(b) == 0 ** |
a != b |
! a.equals(b) |
a <=> b |
a.compareTo(b) |
a > b |
a.compareTo(b) > 0 |
a >= b |
a.compareTo(b) >= 0 |
a < b |
a.compareTo(b) < 0 |
a <= b |
a.compareTo(b) <= 0 |
Note that the "==" operator is not always equivalent to the equals() method.
比如:
def a = null
def b = "foo"
assert a != b
assert b != a
assert a == null
No matter whether a or b is null, java.lang.NullPointerException will not be thrown.
In addition, when comparing objects of different types, the coercion rules are used to convert the numeric type to the largest numeric type. So the following code is valid:
Byte a = 12
Double b = 10
assert a instanceof Byte
assert b instanceof Double
assert a > b