Close

Groovy Operators - Elvis Operator

[Last Updated: Dec 5, 2018]

In Groovy, the Elvis operator is shortening of the Ternary Operator which is handy for returning a 'default' value.

Generally following ternary expression

x = x == null ? x: y

can be reduced to the following Elvis expression:

x ?: y

Example

import java.time.LocalTime;
def  labelTime(String label){
   label = label == null? "N/A" : label;
   return  label + " : " + LocalTime.now();
}

print labelTime(null);
N/A : 03:14:35.254981400

In above example we used Ternary operator in the usual way. Let's use Elvis operator:

import java.time.LocalTime;
def  labelTime(String label){
   label = label?: "N/A"
   return  label + " : " + LocalTime.now()
}

print labelTime(null);
N/A : 03:14:38.065762500

Java does not have Elvis operator. Although Java 8 Optional can be used for the same purpose:

import java.time.LocalTime;
def  labelTime(Optional<String> optionalLabel){
   String label = optionalLabel.orElse("N/A")
   return  label + " : " + LocalTime.now()
}
Optional<String> s = Optional.empty();
print labelTime(s);
N/A : 03:23:32.572604900

See Also