Operators
Prerequisites: Numbers and math
Groovy has Java's operators, plus several that remove whole lines of boilerplate.
Comparison: == means equals
def a = new String('hi')
def b = new String('hi')
println a == b // value equality (calls equals)
println a.is(b) // identity: the same object?
println a === b // identity operator (Groovy 3+)
println 3 <=> 5 // spaceship: -1, 0, or 1
println 'b' <=> 'a'
println 2 in [1, 2, 3]
true
false
false
-1
1
true
In Java, == compares object references, a classic source of bugs with
strings. In Groovy, == compares values (it calls equals, or
compareTo for comparable types). Use is() or === for identity.
Logical operators
def age = 20
def member = false
println age >= 18 && !member
println age < 13 || member
true
false
&& and || short-circuit: the right side runs only when needed.
Null-safe navigation and Elvis
def user = [name: 'Ada', address: null]
println user.address?.city // null instead of an exception
println user.nickname ?: 'no nickname'
def city = user.address?.city ?: 'unknown'
println city
def title = null
title ?= 'Untitled' // assign only if null/false
println title
null
no nickname
unknown
Untitled
?.stops and returnsnullif the left side isnull.?:(the Elvis operator) returns the left side if it's "truthy", otherwise the right side — perfect for defaults.?=assigns only when the variable is null or false (Groovy 5+).
Spread, ternary, and safe index
def people = [[name: 'Ada', age: 36], [name: 'Linus', age: 28]]
println people*.name // spread: call on each element
def n = 7
println n % 2 == 0 ? 'even' : 'odd'
def list = null
println list?[0] // safe index (Groovy 3+)
[Ada, Linus]
odd
null
*. applies a property or method to every item of a list and collects
the results — people*.name is short for people.collect { it.name }.
Common mistakes
- Using
.equalseverywhere out of Java habit —==already does it, and it's null-safe. - Writing
x ?: defaultwhenxmay legitimately be0or'': those are "falsy" too (next lesson), so the default wins. Usex != null ? x : defaultif zero is a valid value.