Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 38 ยท Language Basics

Groovy Operators

Learn Groovy operators: safe navigation ?., Elvis ?:, spread *., spaceship <=>, in and as, method pointers, operator overloading and the precedence rules you need.

Groovy keeps every Java operator and adds a small set of new ones that remove common boilerplate: null checks, defaults, comparisons and loops over collections. Learning these operators is the quickest way to make your code look "Groovy". This lesson covers them one by one, with short examples, and then shows how you can define operators for your own classes.

Groovy blocks are read-only. Java stand-ins below demonstrate the same ideas in code you can run.

Familiar operators

Arithmetic (+ - * / % **), comparison (== != < <= > >=), logic (&& || !), bitwise (& | ^ ~ << >> >>>) and assignment (= += -= ...) work as in Java, with the Groovy twists you met earlier: / gives a decimal, == is equality and ** is power.

Two more that matter:

GROOVY
assert 1 + 2 * 3 == 7
assert 'ab' < 'ac'            // strings are Comparable
def x = 5
x++                           // x is 6
assert !(x == 5)

Safe navigation: ?.

Calling a method on null throws NullPointerException. The safe navigation operator returns null instead:

GROOVY
def person = null
println person?.name          // null (no exception)
println person?.address?.city // null

You can chain it, which replaces nested if checks. It also works for method calls: text?.trim().

The Elvis operator: ?:

The Elvis operator returns the left side if it is "true" by Groovy truth, otherwise the right side. It is a short ternary used for defaults:

GROOVY
def name = input ?: 'anonymous'      // same as input ? input : 'anonymous'
def port = config.port ?: 8080

There is also the Elvis assignment ?=:

GROOVY
def title = null
title ?= 'Untitled'                   // assigns only when title is falsy
println title                         // Untitled

Because Groovy truth treats 0 and empty strings as false, ?: also replaces a legitimate 0 or ''. If zero is meaningful, test for null explicitly: x != null ? x : 10.

The Java stand-in below uses Optional and a ternary to reproduce both operators.

Java Java stand-in: safe navigation and Elvis

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The spread operator: *.

*. calls a method or reads a property on every element of a collection and returns a list:

GROOVY
def names = ['ada', 'linus', 'grace']
println names*.toUpperCase()     // [ADA, LINUS, GRACE]
println names*.length()          // [3, 5, 5]

It is null-safe for the collection elements. The spread-dot is the short version of collect, and it is equivalent to names.collect { it.toUpperCase() }. There is also a spread for arguments, *list, which expands a list into method arguments:

GROOVY
def add(a, b, c) { a + b + c }
def nums = [1, 2, 3]
println add(*nums)               // 6

And in list or map literals: [0, *nums, 4] gives [0, 1, 2, 3, 4].

The spaceship operator: <=>

a <=> b returns -1, 0 or 1 using compareTo. It is perfect for sorting:

GROOVY
assert (1 <=> 2) == -1
assert ('b' <=> 'a') == 1
def people = [[n: 'Ada', a: 36], [n: 'Bob', a: 30]]
println people.sort { x, y -> x.a <=> y.a }*.n    // [Bob, Ada]

Membership and type: in, instanceof, as

GROOVY
assert 3 in [1, 2, 3]
assert !('z' in ['a', 'b'])
assert 5 in 1..10
assert 'text' instanceof String
assert 'x' in String                       // class membership with `in`
assert ([1, 2] as Set) == [2, 1] as Set

in calls isCase, which Groovy defines for collections, ranges, classes, regex patterns and closures, and which also drives switch.

Equality and identity

  • == and != mean value equality (equals or compareTo).
  • a.is(b) tests identity.
  • === and !== exist as identity operators in Groovy 3 and later; many teams prefer is() for readability.

Method pointers: .&

The .& operator takes a reference to an existing method, so you can pass it like a closure:

GROOVY
def shout = String.&toUpperCase
println shout('hi')                       // HI
def twice(s) { s * 2 }
println(['a', 'b'].collect(this.&twice))   // [aa, bb]

Method pointers are handy for passing named methods to collect, each and sort.

Direct field access: .@

obj.name calls getName() when it exists. obj.@name bypasses it and reads the field. It is rarely needed but explains why a property with custom getter behaves differently inside and outside the class.

Range operators

1..5 is inclusive, 1..<5 excludes the end, and ranges can go downward: 5..1. See Ranges and Sets for more.

Operator overloading

Every operator maps to a method name. If your class defines the method, the operator works:

Operator Method
a + b a.plus(b)
a - b a.minus(b)
a * b a.multiply(b)
a / b a.div(b)
a % b a.mod(b)
a ** b a.power(b)
a << b a.leftShift(b)
a[b] a.getAt(b)
a == b a.equals(b)
a <=> b a.compareTo(b)
-a a.negative()
a as T a.asType(T)
GROOVY
class Money {
    BigDecimal amount
    Money plus(Money other) { new Money(amount: amount + other.amount) }
    String toString() { "\$${amount}" }
}

println new Money(amount: 5) + new Money(amount: 7)   // $12

The Java stand-in cannot overload +, but it shows the method each operator maps to, which is exactly what Groovy calls.

Java Java stand-in: the methods behind operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Precedence in practice

You rarely need the full precedence table. Remember: ** binds tighter than *, comparison binds tighter than &&, and ?: and assignments bind loosely. When in doubt, add parentheses.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does user?.profile?.email return when user is null?

    The safe navigation operator stops the chain and evaluates to null instead of throwing.
  2. 2. What is the result of '' ?: 'default'?

    An empty string is false by Groovy truth, so Elvis returns the right-hand value.
  3. 3. What does ['a', 'bb']*.size() produce?

    The spread-dot calls size() on each element and collects the results in a list.
  4. 4. Which method must a class define for a + b to work on its instances?

    Groovy maps + to the method plus. Other operators have similar fixed names such as minus, multiply and leftShift.

Summary

  • ?. avoids null pointer errors, ?: supplies defaults, *. applies an operation to every element.
  • <=> compares, in tests membership, as converts, .& makes method pointers.
  • == is equality and is() is identity.
  • Every operator is a method call, so your own classes can support +, -, [], << and more.

Next: Control Flow and Truth