Often in Groovy programming we need to assign a receiving (target) variable to the value of another variable, if the variable is not
deemed false by Groovy (e.g., a number with a value of zero, a zero-length string
or an object that is null). If the variable is false, then we typically need to assign a true value to the receiver that clearly indicates the sending variable was false.
We could use an
if..else or a ternary operator but in Groovy a more convenient
way is to use the Elvis operator, i.e.,
?:. In this topic you will find out when to use this operator.
To learn when to use the Elvis operator in Groovy follow these 4 steps:
def fullName = "Stephen Withrow" def otherName = "" def age20 = 20 def age0 = 0 // ternary operator: def result = fullName ? fullName : "false" println ("Ternary result: $result") // Elvis operator: result = fullName ?: "false" println ("Elvis operator result: $result") // use Elvis operator from here to the end result = otherName ?: "false" println ("Name of length zero: $result") def ageResult = age20 ?: -1 println ("Age with non-zero value: $ageResult") ageResult = age0 ?: -1 println ("Age with value of zero: $ageResult")
fullNameas the assigned value should the variable evaluate to true. The Elvis operator assumes
fullNameis the value to assign when the variable is true. Other Elvis operator tests are present to show the result when the name is false (e.g., a zero length value) and when ages are true and false (e.g., a value of zero).