...
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
Code Block |
---|
language | groovy |
---|
title | Unary operators |
---|
linenumbers | true |
---|
|
int x = 10
x++ //returns 11
++x //returns 12
x-- //returns 11
--x //returns 10 |
Code Block |
---|
language | groovy |
---|
title | Arithmetic operators |
---|
linenumbers | true |
---|
|
1 + 2 //returns 3
3 / 2 //returns 1.5
10 % 3 //returns 1
|
Code Block |
---|
language | groovy |
---|
title | Assignment arithmetic operators |
---|
linenumbers | true |
---|
|
def a = 5
b = a += 3 //returns 8
def c = 5
c *= 3
c == 15
|
Code Block |
---|
language | groovy |
---|
title | Range operator |
---|
linenumbers | true |
---|
|
def range = 5..9
range[3] == 8 |
Code Block |
---|
language | groovy |
---|
title | Relational operators |
---|
linenumbers | true |
---|
|
a > b
b - 3 == a
b + 3 != a
|
Code Block |
---|
language | groovy |
---|
title | Logical operators |
---|
linenumbers | true |
---|
|
x && y
x || y
!x |
Code Block |
---|
language | groovy |
---|
title | Conditional operators |
---|
linenumbers | true |
---|
|
!true == false
!'' == true |
...
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 |
---|
language | groovy |
---|
linenumbers | true |
---|
|
def text = "Test"
if (text!=null && text.length()>0) {
result = text
} else {
result = 'Empty'
} |
you can simplify it to:
Code Block |
---|
language | groovy |
---|
title | Ternary operator |
---|
linenumbers | true |
---|
|
def text = "Test"
text ? text : 'Empty' |
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 |
---|
language | groovy |
---|
title | Elvis operator |
---|
linenumbers | true |
---|
|
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 |
---|
language | groovy |
---|
linenumbers | true |
---|
|
if(employee){
employee.getSalary()
} |
Instead, you can write it as:
...
language | groovy |
---|
linenumbers | true |
---|
...
Include Page |
---|
| JMWE:Operators in Groovy |
---|
| JMWE:Operators in Groovy |
---|
|