Skip to content

Operators

Groovy has many operators. Some are reused for different purposes in different contexts. In particular, many are used for operator overloading, allowing the operator to be used on valid objects.

You can read more about operators on the official documentation.

Types of Operators

Arithmetic

The basic math operators are the same as they always are.

SymbolNameOperation
a + bAdditionadd a and b
a - bSubtractionsubtract b from a
a / bDivisiondivide a by b
a * bMultiplicationmultiple a by b
a % bRemainderget the remainder of dividing a by b
a ** bPowera to the power of b

Compound Assignment

You can use several different operators in conjunction with an equal sign to update a variable. This will also implicitly cast the output into the same type as a.

a [op]= b is equivalent to a = a [op] b.

SymbolNameOperation
a = bAssignmenta = b
a += bAdditiona = a + b
a -= bSubtractiona = a - b
a /= bDivisiona = a / b
a *= bMultiplicationa = a * b
a %= bRemaindera = a % b
a **= bPowera = a ** b
a ?= bElvisa = a ?: b
a &= bBitwise Anda = a & b
a |= bBitwise ORa = a | b
a <<= bLeft Shifta = a << b
a >>= bRight Shifta = a >> b
a >>>= bRight Shift Unsigneda = a >>> b

Increment/Decrement

There are two shorthand ways to write a = a + 1 and two to write a = a - 1.

Warning

The two ways differ in what value they return - a++ returns the value of a before being increased, while ++a returns the value of a after being increased. When interacting with these operators, to avoid confusion, you should use them as a standalone statement -

groovy
def x = 5
x++
Code.run(x) // do this
Code.run(x++) // don't do this
SymbolNameOperation
a++Postfix Incrementreturn a; a = a + 1
a--Postfix Decrementreturn a; a = a - 1
++aPrefix Incrementa = a + 1; return a
--aPrefix Decrementa = a - 1; return a

Equality

Compare two values with each other.

SymbolNameOperation
a == bEqualstrue if a is the same as b
a != bNot Equalstrue if a is not the same as b
a < bLess Thantrue if a is less than b
a <= bLess Than or Equal totrue if a is less than or equal to b
a > bGreater Thantrue if a is greater than b
a >= bGreater Than or Equal totrue if a is greater than or equal to b
a === bIdenticaltrue if a is identical to b
a !== bNot Identicaltrue if a is not identical to b

Logical

Returns a boolean value based on the outcome of the equation. The AND and OR operators will short-circuit, and not run the right hand side if it is not needed. This means you can do things like bool && run(), and run() will only be called if bool is true.

SymbolNameOperation
a && bLogical Andtrue if both a and b are true
a || bLogical Ortrue if either a or b are true
!aLogic Nottrue if a is false

Bitwise

Bitwise operations are named as such because they directly manipulate bits. Note that bitwise operators do not short-circuit, and will always check both sides of the equation.

SymbolName
a & bBitwise AND
a | bBitwise OR
a ^ bBitwise XOR
a ~ bBitwise Negation
a << bLeft Shift
a >> bRight Shift
a >>> bRight Shift Unsigned

Null Handling

There are some operators to help with handling null, and avoid NullPointerExceptions.

SymbolNameOperation
a ? b : cTernaryreturns b if a is true and c if a is false
a ?: bElvisreturns b if a is false, otherwise returns a
a?.bSafe Navigationused on an object, will return null if a is null, otherwise will return b
a?[b]Safe Indexused on an array, will return null if a is null or b is outside of the array

Field Access

SymbolNameOperation
a.bField accessreturns getB if the method exists, otherwise returns the field b
a.@bDirect field accessreturns the field b instead of the method getB()

Method Reference

SymbolNameOperation
a.&bMethod pointerreturns a reference to the method b instead of calling it
a::bMethod referencefunctionally an alias of a.&b

Regex

SymbolNameOperation
~aPatternparses String a into a Regex Pattern
a =~ bFindruns ~b, then creates a Matcher against String a
a ==~ bMatchruns a =~ b, then returns true if there were any matches

Spread

You can manipulate an array of objects

SymbolNameOperation
a*.bSpreadcalls b on all items in array a
*aArgumentsexpands the array a into individual elements when calling a method

Range

You can create a range, typically a range of numbers, in a shorthand way. This is typically used as part of a loop or getting a subset of a list.

SymbolNameOperation
a..bRangeRange from a to b, inclusive on both bounds
a<..bRangeRange from a to b, exclusive on the lower bound and inclusive on the upper bound
a..<bRangeRange from a to b, inclusive on the lower bound and exclusive on the upper bound
a<..<bRangeRange from a to b, exclusive on both bounds

Syntax Sugar

SymbolNameOperation
<>Diamondsyntax sugar relating to generic types

Operator Overloading

Groovy has a mechanism where a symbol can be transformed into calling a method on an object. This is a full table of these Operators, and what method they call.

SymbolMethod Called
a + ba.plus(b)
a - ba.minus(b)
a * ba.multiply(b)
a / ba.div(b)
a % ba.mod(b)
a ** ba.power(b)
a | ba.or(b)
a & ba.and(b)
a ^ ba.xor(b)
<=>a.compareTo(b)
a == ba.equals(b)
a as ba.asType(b)
a()a.call()
a[b]a.getAt(b)
a[b] = ca.putAt(b, c)
a in bb.isCase(a)
a << ba.leftShift(b)
a >> ba.rightShift(b)
a >>> ba.rightShiftUnsigned(b)
a++a.next()
a--a.previous()
+aa.positive()
-aa.negative()
~aa.bitwiseNegate()

Contributors

Changelog

© 2024 CleanroomMC. All Rights Reserved.