Recently the Groovy team introduced a new operator to the Groovy language. It is called the Elvis operator. There is one thing I particularly like about this operator. It’s name.
To bad the Elvis operator is only a shortening of Java’s ternary operator, written like ?:. One use-case for the operator is returning a ‘sensible default’ value if an expression resolves to false or null. A simple example might look like this:
groovy:000> name = null
groovy:000> displayName = name ?: “anonymous”
I had a good laugh about it with some people at JavaPolis, and forgot about it. Until I noticed something while reading the expressions chapter in the PickAxe (I’m trying to boost my Ruby knowledge).
In Ruby anything which isn’t nil is true in an expression. Due to this behavior the result of a shortcut expression doesn’t have to be a boolean but is actually the value which evaluated to true (in Groovy the result is a boolean). This means Ruby implicitly has a ‘Elvis’ operator.
irb(main):069:0> name = nil
irb(main):070:0> displayName = name || “anonymous”
Even better, Ruby allows you to use the shortcut OR in combination with the assignment operator:
irb(main):072:0> name = nil
irb(main):073:0> name ||= “anonymous”
irb(main):074:0> name = “peter”
irb(main):075:0> name ||= “anonymous”
Funny to see how a slightly different behavior of something like to or operator makes it even more useful!