Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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:

Table of Contents

Typical operators

Code Block
languagegroovy
titleUnary operators
linenumberstrue
int x = 10

x++ //returns 11
++x //returns 12
x-- //returns 11
--x //returns 10

...

Panel
titleTernary operator

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

Instead of:

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

you can simplify it to:

Code Block
languagegroovy
titleTernary operator
linenumberstrue
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:

Code Block
languagegroovy
titleElvis operator
linenumberstrue
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:

Code Block
languagegroovy
linenumberstrue
if(employee){
  employee.getSalary()
}

...