Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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.

Table of Contents
maxLevel8
minLevel3

Arithmetic and Conditional Operators

...

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

Code Block

def expression = false
assert !expression

...

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:

Code Block

parent*.action                             //equivalent to:
parent.collect{ child -> child?.action }

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:

Code Block

assert ['cat', 'elephant']*.size() == [3, 8]

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:

Code Block

class Person { String name }
class Twin {
  Person one, two
  def iterator() {
    return [one, two].iterator()
  }
}

def tw = new Twin(one: new Person(name:'Tom'),
                  two: new Person(name:'Tim'))
assert tw*.name == ['Tom', 'Tim']
// expanded equivalent of above:
assert tw.collect{ it.name } == ['Tom', 'Tim']

...

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

Code Block

class X
{
    def field
}

x = new X()
x.field = 1
println x.field    // 1

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

Code Block

class X
{
    def field

    def getField()
    {
        field += 1
    }
}

x = new X()
x.field = 1
println x.field   // 2

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

Code Block

println x.@field   // 1

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

  • getAt(index) and

    setAt

    putAt(index, value) for the subscript operator (e.g. foo[1] or foo['bar'], i.e. index is either an int or String)

  • Range Operator (..) - see Collections#Collections-RangesMembership Operator ( Collections
  • isCase() for the membership operator (in)

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:

Code Block

def gender = user.male ? "male" : "female"  //traditional ternary operator usage

def displayName = user.name ?: "Anonymous"  //more compact Elvis 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:

Code Block

def user = User.find( "admin" )           //this might be null if 'admin' does not exist
def streetName = user?.address?.street    //streetName will be null if user or user.address is null - no NPE thrown

...

Operator Name

Symbol

Description

Spaceship

<=>

Useful in comparisons, returns -1 if left is smaller 0 if == to right or 1 if greater than the right

Regex find

=~

Find with a regular expresion? See  Regular Expressions

Regex match

==~

Get a match via a regex? See See Regular Expressions

Java Field Override

.@

Can be used to override generated properties to provide access to a field

Spread

*.

Used to invoke an action on all items of an aggregate object

Spread Java Field

*.@

Amalgamation of the above two

Method Reference

.&

Get a reference to a method, can be useful for creating closures from methods

asType Operator

as

Used for groovy casting, coercing one type to another.

Membership Operator

in

Can be used as replacement for collection.contains()

Identity Operator

is

Identity check. Since == is overridden in Groovy with the meaning of equality we need some fallback to check for object identity.

Safe Navigation

?.

returns nulls instead of throwing NullPointerExceptions

Elvis Operator

?:

Shorter ternary operator