In this post under Spring SpEl, I will explain with example the purpose of Elvis operator.
Lets say you have below statement written using ternary operator
String result = (data != null) ? data : null;
In the above statement “data” variable is of type String.
So we are checking if “data” is not null, then return “data” itself or else null.
So in statements where you are checking a variable is not null or not false and returning the same variable when the condition is true.
We can replace that statement written using ternary operator with elvis operator as shown below
So basically elvis operator is a short form of ternary operator only when we are checking whether a variable is not null or not false and returning the same variable when the condition is true.
String result = data?:null;
Below is the main class showing its usage for your reference
Main class
package spel.package24;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
public class Example24 {
public static void main(String[] args) {
Employee employee = new Employee(1, "Sean Mendes", 1000);
SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
Expression expression = spelExpressionParser.parseExpression("name != null ? name : 'John Doe'");
String result = expression.getValue(employee, String.class);
System.out.println("Result of ternary operator: " + result);
expression = spelExpressionParser.parseExpression("name ?: 'John Doe'");
result = expression.getValue(employee, String.class);
System.out.println("Result of elvis operator: " + result);
}
}
In the above code, at line 10, I used ternary operator.
Same expression is replaced by elvis operator at line 14.
In both the cases the output will be “Sean Mendes”.
Below is the output
Output
Result of ternary operator: Sean Mendes
Result of elvis operator: Sean Mendes
In this way we can use elvis operator.