| |
| 1 Operator overloading in Groovy |
| |
| Groovy supports operator overloading which makes working with Numbers, |
| Collections, Maps and various other data structures easier to use. |
| |
| Various operators in Groovy are mapped onto regular Java method calls on objects. |
| This allows you the developer to provide your own Java or Groovy objects which can take |
| advantage of operator overloading. The following table describes the operators |
| supported in Groovy and the methods they map to. |
| |
| {table} |
| Operator | Method |
| a + b | a.plus(b) |
| a - b | a.minus(b) |
| a * b | a.multiply(b) |
| a / b | a.divide(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) |
| {table} |
| |
| Note that all the following comparison operators handle nulls gracefully avoiding |
| the throwing of {api:java.lang.NullPointerException} |
| |
| {table} |
| Operator | Method |
| a == b | a.equals(b) |
| a != b | ! a.equals(b) |
| a === b | a == b in Java (i.e. a and b refer to same object instance) |
| 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 |
| {table} |
| |
| 1.1 Notes about operations |
| |
| Also in Groovy comparison operators handle nulls gracefully. So that a == b will never throw a |
| NullPointerException whether a or b or both are null. |
| |
| {code:groovy} |
| a = null |
| b = "foo" |
| |
| assert a != b |
| assert b != a |
| assert a == null |
| {code} |
| |
| In addition when comparing numbers of different types then type coercion rules apply to convert |
| numbers to the largest numeric type before the comparison. So the following is valid in Groovy |
| |
| {code:groovy} |
| Byte a = 12 |
| Double b = 10 |
| |
| assert a instanceof Byte |
| assert b instanceof Double |
| |
| assert a > b |
| {code} |