Versions Compared

Key

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

...

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
Code Block
languagegroovy
titleArithmetic operators
linenumberstrue
1 + 2 //returns 3
3 / 2 //returns 1.5
10 % 3 //returns 1
Code Block
languagegroovy
titleAssignment arithmetic operators
linenumberstrue
def a = 5 
b = a += 3 //returns 8

def c = 5
c *= 3
c == 15
Code Block
languagegroovy
titleRange operator
linenumberstrue
def range = 5..9
range[3] == 8
Code Block
languagegroovy
titleRelational operators
linenumberstrue
a > b
b - 3 == a
b + 3 != a
Code Block
languagegroovy
titleLogical operators
linenumberstrue
x && y
x || y
!x
Code Block
languagegroovy
titleConditional operators
linenumberstrue
!true == false
!'' == true

...

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()
}

Instead, you can write it as:

...

languagegroovy
linenumberstrue

...

Include Page
JMWE:Operators in Groovy
JMWE:Operators in Groovy