Java Reference
In-Depth Information
written has some repetition in it. After all, I want to use name if it's available, so why do I
have to repeat myself?
That's where the Elvis operator comes in. Here's the revised code:
String displayName = name ?: 'default'
The Elvis operator is the combination of a question mark and a colon formed by leaving
outthevalue inbetween them intheternary operator.Theidea isthat ifthevariable infront
of the question mark is not null, use it. The ?: operator is called Elvis because if you turn
your head to the side, the result looks vaguely like the King:
def greet(name) { "${name ?: 'Elvis'} has left the building" }
assert greet(null) == 'Elvis has left the building'
assert greet('Priscilla') == 'Priscilla has left the building'
The greet method takes a parameter called name and uses the Elvis operator to determ-
ine what to return. This way it still has a reasonable value, even if the input argument is
null. [ 15 ]
15 Thank you, thank you very much.
B.6.4. Safe de-reference
There's one final conditional operator that Groovy provides that saves many lines of cod-
ing. It's called the safe de-reference operator, written as ?. .
The idea is to avoid having to constantly check for nulls. For example, suppose you have
classes called Employee , Department , and Location . If each employee instance has
a department, and each department has a location, then if you want the location for an em-
ployee, you would write something like this (in Java):
Location loc = employee.getDepartment().getLocation()
But what happens if the employee reference is null? Or what happens if the employee
hasn'tbeenassignedadepartment,sothe getDepartment methodreturns null ?Those
possibilities mean the code expands to
 
Search WWH ::




Custom Search