Groovy : What is Elvis Operator and difference b/w Elvis and Ternary operator
Ternary Operator
Ternary Operator is the short hand of the if-else block
, where a condition is evaluated to true or false and following statement is executed.
Syntax of the ternary operator is below
<boolean expression> ? <executed when condition is true> : <executed when condition is false>
A typical example of if-else block is shown below where we check if a variable is null or not.
String s = "hello"
if( s != null )
println s
else
println "not found"
We can replace the above code with the ternary
operator as shown below
String s = "hello"
println s !=null ? s : "not found"
Here, the variable s
is assigned a string hello
and condition s!=null
evaluates to true hence the statement after ?
is executed which returns s
itself.
Elvis Operator
Elvis operator is the short hand of the Ternary operator
explained above. In this operator we do not specify the true
condition. The true condition is will evauate to the expression itself.
Syntax of the elvis
operator is
<expression> ?: <executed when condition is false>
Let's see an example
String s = "hello"
println s!=null ?: "not found" // true
println s ?: "not found" // hello
println null ?: "not found"
In the above example,
- Expression
s!=null
evaluates to true, and will print true - Expression
s
in will evaluate to true according to Groovy Truth, and will returnhello
, the value of variables
- Expression
null
will evaluate to false according to Groovy Truth and will returnnot found
string
No comments: