Operators
In general all operators supported in Java are identical in Groovy. Groovy goes a step further by allowing you to customize behavior of operators on Groovy types.
TODO make this page a child of the User Guide, and make Operator Overloading a child of this page.
Arithmetic Operators
See Operator Overloading for a list of the common arithmetic operators that Groovy supports.
Conditional Operators
TODO the ! (not) operator; link to Groovy Truth documentation
Elvis Operator (?:)
The "Elvis operator" is a shortening of Java's ternary operator. One instance of where this is handy is for returning a 'sensible default' value if an expression resolves to false or null. A simple example might look like this:
Safe Navigation Operator (?.)
The Safe Navigation operator is used to avoid a NullPointerException. Typically when you have a reference to an object you might need to verify that it is not null before accessing methods or properties of the object. To avoid this, the safe navigation operator will simply return null instead of throwing an exception, like so:
Collection-based Operators
Spread Operator (*.)
The Spread Operator is used to invoke an action on all items of an aggregate object. It is equivalent to calling the collect method like so:
The spread operator may be used a method call or property access, and returns a list of the items returned from each child call. So you may effectively override the spread operator by implementing a custom collect method.
- getAt() and setAt() for the subscript operator (e.g. foo[1])
- Range Operator (..) - see Collections#Collections-Ranges
- Membership Operator (in)
Object- Related Operators
- invokeMethod and get/setProperty (.)
- Method Reference (.&)
- 'as' - "manual coercion" -
asType(t)method - Groovy == (
equals()) behavior.- "is" for identity
- Instanceof (just for completeness – exactly the same as Java)
Regular Expression Operators
- find (=~)
- match (==~)