Operators in Groovy
Learn arithmetic, comparison, logical, and Groovy-specific operators including Elvis, safe navigation, spaceship, range, and regex with Docker-ready examples
Introduction
Operators are the verbs of a programming language—they let you combine values, compare them, and express logic. Groovy inherits the full operator set from Java but layers on a handful of its own conveniences that make code dramatically more concise. Because Groovy is a multi-paradigm, dynamically typed (with optional static typing) language for the JVM, its operators work polymorphically: the same + can add numbers, concatenate strings, or merge lists depending on the operands.
A few aspects of Groovy’s operator design surprise newcomers. Dividing two integers with / does not produce an integer result—Groovy returns a BigDecimal to preserve precision. Comparison with == calls .equals() instead of doing reference comparison like Java. And uniquely Groovy operators like Elvis (?:), safe navigation (?.), spaceship (<=>), and ranges (..) eliminate huge amounts of defensive boilerplate.
In this tutorial you’ll work through the standard operator categories and then meet the Groovy-only operators that you’ll see constantly in Gradle build scripts, Jenkins pipelines, and Spock specifications.
Arithmetic, Comparison, Logical, and Assignment Operators
The first program covers the operators you’d recognize from any C-family language, plus a few quirks specific to Groovy’s numeric model.
Create a file named operators.groovy:
| |
A few things to notice:
17 / 5evaluates to3.4, aBigDecimal. Useintdiv()when you want integer truncation.**is the power operator; Java has no equivalent.==on strings tests content equality. To test object identity (Java’s==), useis():a.is(b).*on aStringrepeats it, and+concatenates. These also work for lists.
Groovy-Specific Operators
Now we’ll meet the operators you don’t get in Java. Each one replaces a multi-line idiom with a single character or two.
Create a file named operators_special.groovy:
| |
Each of these collapses what would be several lines in Java:
- Elvis (
?:) replacesx != null ? x : default. - Safe navigation (
?.) replacesx == null ? null : x.method(). - Spaceship (
<=>) is the natural fit forComparatorlambdas and sort keys. - Range (
..) produces an iterable sequence; combined within, it expresses membership cleanly. =~creates ajava.util.regex.Matcher;==~returnstrueonly when the entire string matches.
Operator Precedence
Groovy’s precedence rules follow Java’s closely. From highest to lowest, the groups you’ll encounter most often:
- Unary:
!,-(negation),++,-- - Power:
** - Multiplicative:
*,/,% - Additive:
+,- - Range:
..,..< - Relational:
<,>,<=,>=,in,instanceof - Equality:
==,!=,<=> - Logical AND:
&& - Logical OR:
|| - Ternary / Elvis:
?: - Assignment:
=,+=,-=, etc.
When in doubt, add parentheses—they cost nothing and make intent explicit.
Running with Docker
| |
Expected Output
Running operators.groovy:
a + b = 22
a - b = 12
a * b = 85
a / b = 3.4
a.intdiv(b) = 3
a % b = 2
a ** b = 1419857
a == b: false
a != b: true
a > b: true
'cat' == 'cat': true
t && f: false
t || f: true
!t: false
x += 5 -> 15
x *= 2 -> 30
x -= 6 -> 24
Hi there!
HiHiHi
Running operators_special.groovy:
5 <=> 3: 1
3 <=> 5: -1
5 <=> 5: 0
Name: Anonymous
Length: null
Range size: 5
3 in range: true
9 in range: false
First digits found: 4
'12345' ==~ /\d+/: true
'abc12' ==~ /\d+/: false
Key Concepts
/is BigDecimal division, not integer truncation—use.intdiv()when you want a whole-number result.==calls.equals()by default; reference identity is.is(). This is the opposite of Java and one of the most common stumbling points for Java developers.**is the power operator, eliminating the need forMath.pow()in most cases.- Elvis (
?:) and safe navigation (?.) are everywhere in idiomatic Groovy—they replace null-check boilerplate. - Spaceship (
<=>) returns-1,0, or1, making it the idiomatic key for sorting andComparableimplementations. - Ranges (
..inclusive,..<exclusive) are first-class iterables and pair naturally with theinmembership operator. =~returns aMatcher;==~returns aBoolean—remember “tilde for whole match” by the extra=.- Operator overloading is supported: define
plus(),minus(),multiply(),compareTo(), etc., on your own classes and Groovy will wire them up to+,-,*, and<=>.
Running Today
All examples can be run using Docker:
docker pull groovy:4.0-jdk17-alpine
Comments
Loading comments...
Leave a Comment