Elvis operator
Dierk König
dierk.koenig at canoo.com
Thu Jul 16 03:13:28 PDT 2009
Hi,
I made the term "Elvis operator" popular through the "Groovy in
Action" and I would like to clarify its
meaning because it is often confused with the "Null-safe dereferencing
operator".
This has led to numerous misquotes in communications, conference
talks, and podcasts like
in episode 253 of the JavaPosse.
The Elvis operator is a shortcut for the ternary "if" operator when
the "true" case should
yield the value of the conditional.
The following lines are equivalent(1) in Groovy
if (a) then a else b // classic if
a ? a : b // ternary if
a ?: b // Elvis
This construction only makes sense in Groovy because "a" can be of any
arbitrary type -
and is not restricted to be a boolean expression. The boolean value
inside the
conditional is calculated by the rules of the "Groovy truth", where
objects can be
casted to boolean such that e.g. null objects are treated as "false"
just like
empty Strings, Maps, and Lists.
Therefore, an Elvis expression does not necessarily return a boolean
in Groovy
but can be of any runtime type allowing constructions like
String s = a ?: "n/a"
to set a reference to a default value if no proper value is available.
The same use comes handy in method calls like
myMethod( a ?: "n/a" )
The discussion above makes me think that an Elvis operator would be much
less useful in Java...
Elvis is often confused with the null-safe dereferencing of objects
like in
a?.foo()
which does not throw NPE if "a" is null but returns null without
evaluating foo().
This is __**NOT**__ an Elvis operator unless you assume a one-eyed
Elvis !!!
I'm glad to see that in recent posts on this list, the distinction has
much improved.
all the best
Dierk
(1) "equivalent" does not mean "identical" because in case of the
Elvis operator, the
"a" expression is only evaluated once.
P.S. Needless to say: there is only one true Elvis!
More information about the coin-dev
mailing list