When to Use the Elvis Operator in Groovy
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:
- Open your text editor and type in the following lines of Groovy code:
The script sets up several variables that we must assign to a receiver if the variable is true. If the variable is false, then the receiver must have a value (e.g.,"false" for names, -1 for ages) to clearly indicate the variable is false. The Elvis operator is intended for this task. The first use of the Elvis operator is preceded with the ternary operator so that you can see the savings in code using the Elvis operator, i.e., you don't have to code
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")
fullName
as the assigned value should the variable evaluate to true. The Elvis operator assumesfullName
is 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). - Save your file as
ElvisOperator.groovy
. - In the command prompt, type in the command to interpret and run your script:
The output displays the result of using the ternary operator followed by the results from applying the Elvis operator to the variables as described earlier.