Groovy Elvis Operator

Groovy Elvis Operator

In Java we do  so many null checks 
If (somevalue != null) {
    val = somevalue
} else { 
    val = defaultValue 
Instead of writing if (something != null) { ... }  we write if (something) { ... }
Well this type of branching logic is precisely why we have the ternary operator in both Java and Groovy.  It turns our 4 lines of if/else logic into a single line like:
val = something ? something : defaultValue
The syntax and logic for the ternary operator is the same in Groovy as it is in Java;
  (Condition) ? Value-If-True : Value-If-False   
Instead of writing:  val = something ? something : defaultValue
We could write:  val = something ?: defaultValue
A more clear example would be as follows:
def actor
def defaultactor = actor?: "Ven Diesel"
assert defaultrockstar == "Ven Diesel"

Elvis operator useful but repetition is still around it so it could be like 
ef actor
def defaultactor = actor?: "Ven Diesel"
further we can simplify like 
def actor
actor?= "Ven Diesel"
This would be effectively the same as:
actor= actor? actor: "Ven Diesel" 
actor = actor?: "Ven Diesel"


Popular posts from this blog

Conversion from Clob To String in java and Vice versa

Portable Java 8/ JDK8 setup without admin rights

Multi Threading , Producer consumer problem in Java