Operators in Groovy

Groovy supports all typical operators of Java, such as the Unary operators, Arithmetic operators, Assignment operators, Logical operators, Relational operators and Conditional operator. See below for examples using some of the operators. For more information, see any Java documentation.

Apart from these, Groovy also features operators specific to the Groovy language such as the Safe navigation operator and the Elvis operator.

On this page:

Typical operators

Unary operators
int x = 10

x++ //returns 11
++x //returns 12
x-- //returns 11
--x //returns 10
Arithmetic operators
1 + 2 //returns 3
3 / 2 //returns 1.5
10 % 3 //returns 1
Assignment arithmetic operators
def a = 5 
b = a += 3 //returns 8

def c = 5
c *= 3
c == 15
Range operator
def range = 5..9
range[3] == 8
Relational operators
a > b
b - 3 == a
b + 3 != a
Logical operators
x && y
x || y
!x
Conditional operators
!true == false
!'' == true
Ternary operator

The ternary operator is a shortcut expression that is equivalent to an if/else branch assigning some value to a variable.

Instead of:

def text = "Test"
if (text!=null && text.length()>0) {
    result = text
} else {
    result = 'Empty'
}

you can simplify it to:

Ternary operator
def text = "Test"
text ? text : 'Empty'

Operators specific to Groovy

There are notable operators that are specific only to the Groovy language; like the Elvis operator and the Safe Navigation Operator

Elvis operator

Elvis operator is a shortening of the ternary operator. You need not have to repeat the value you want to assign. You can simplify the above example to:

Elvis operator
def text = "Test"
text ?: 'Empty'

Safe navigation operator

The Safe Navigation operator is used to avoid a NullPointerException. 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. Using this operator, you can avoid this and directly return a null.

Normally you would have to:

if(employee){
  employee.getSalary()
}

Instead, you can write it as:

employee?.getSalary()