Groovy is good at shortening normal Java statements. The Elvis operator is to shorten the ternary operator. If we have a sensible default when the value is null or false (following Groovy truth rules) we can use the Elvis operator. And why is it called the Elvis operator? Turn your head to the left and you will know.
def sampleText // Normal ternary operator. def ternaryOutput = (sampleText != null) ? sampleText : 'Hello Groovy!' // The Elvis operator in action. We must read: 'If sampleText is not null assign // sampleText to elvisOuput, otherwise assign 'Viva Las Vegas!' to elvisOutput. def elvisOutput = sampleText ?: 'Viva Las Vegas!'
4 comments:
While the Elvis operator is really an advantage, it is a little more complicated - and stronger - than suggest by bove description.
1. Elvis doesn't check for a null value but only for Groovy truth, treating empty Strings, empty collections etc. as false values. So in your example sampleText will also be replaced when it is not null but an empty String.
2. The real strength of the Elvis operator comes into play when the logical expression is something complicated with side effects. Using the normal ternary operator, you had to evaluate the expression first, store it in a temporary variable, and then make the decision. Elvis evaluates the expression only once, so you need no temporary value. An exact translation of 'a:?b' is not simply 'a?a:b' but rather something like '{def x=a; x?x:b'}'.
So Elvis is only for null-checking ?
I have some problems understanding the result of this (in 1.7b1):
def sampleText = 1
def elvisOutput = (sampleText > 2 ? 333 :444)
println elvisOutput
Do you get 444 too ?
@JST: thank you for your comment. I changed the blog post to include the check for Groovy truth.
@Rusco: Elvis doesn't only check for null, but also follows Groovy truth rules. In your example sampleText > 2 return false, so 444 is displayed.
Post a Comment