Groovy supports operator overloading which makes working with Nu= mbers, Collections, Maps and various other data structures easier to use.=20

Various operators in Groovy are mapped onto regular Java method calls on=
objects.

This allows you the developer to provide your own Java or G=
roovy objects which can take advantage of operator overloading. The followi=
ng table describes the operators supported in Groovy and the methods they m=
ap to.

=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20

=20
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] =3D 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() |

Note that all the following comparison operators handle nulls gracefully= avoiding the throwing of java.lang.NullPointerException

=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20

=20
Operator | Method |
---|---|

a =3D=3D b | a.equals(b) or a.compareTo(b) =3D=3D 0 ** |

a !=3D b | ! a.equals(b) |

a <=3D> b | a.compareTo(b) |

a > b | a.compareTo(b) > 0 |

a >=3D b | a.compareTo(b) >=3D 0 |

a < b | a.compareTo(b) < 0 |

a <=3D b | a.compareTo(b) <=3D 0 |

** Note: The =3D=3D operator doesn't always exactly match the .equals() = method. You can think of them as equivalent in most situations. In situatio= ns where two objects might be thought "equal" via normal Groovy &= quot;coercion" mechanisms, the =3D=3D operator will report them as equ= al; the .equals() method will not do so if doing so would break the normal = rules Java has around the equals method. Expect further improvements to Gro= ovy over time to provide clearer, more powerful and more consistent behavio= r in this area.

=20Also in Groovy comparison operators handle nulls gracefully. So that a = =3D=3D b will never throw a NullPointerException whether a or b or both are= null.

=20=20

def a =3D null def b =3D "foo" assert a !=3D b assert b !=3D a assert a =3D=3D null=20

In addition when comparing numbers of different types the type coercion = rules apply to convert numbers to the largest numeric type before the compa= rison. So the following is valid in Groovy

=20=20

Byte a =3D 12 Double b =3D 10 assert a instanceof Byte assert b instanceof Double assert a > b=20