Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 27 Next »

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.

Arithmetic and Conditional Operators

See Operator Overloading for a list of the common operators that Groovy supports.

In addition, Groovy supports the ! (not) operator as follows:

For more details about how expressions are corced to a boolean value, see: Groovy Truth.

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 action may either be a method call or property access, and returns a list of the items returned from each child call. As an example:

The Spread operator will work as expected with most of the aggregate-like classes within Groovy. You can also customize your own classes to use it by defining your own iterator() method as this example shows:

Object-Related Operators

  • invokeMethod and get/setProperty (.)
  • Java field (.@)
  • The spread java field (*.@)
  • Method Reference (.&)
  • 'as' - "manual coercion" - asType(t) method
  • Groovy == ( equals() ) behavior.
    • "is" for identity
  • The instanceof operator (as in Java)
Java field (.@)

Groovy dynamically creates getter method for all your fields that can be referenced as properties:

You can override these getters with your own implementations if you like:

The @ operator allows you to override this behavior and access the field directly, so to extend the previous sample:

It should be mentioned that, while interesting, this is probably not a good thing to do unless you really need to. Overriding a public interface to access the internal state of an object probably means you are about to break something. Not even recommended for use in tests since it increases coupling unnecessarily.

Other Operators

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:

Regular Expression Operators

  • find (=~)
  • match (==~)

For more details, see: Regular Expressions

  • No labels