Java Reference
In-Depth Information
Listing B-36 illustrates using the Java ternary and Elvis operators in Groovy.
Listing B-36. Using the Elvis Operator
def firstName = author.firstName == null ? "unknown" : author.firstName // Java ternary
def firstName2 = author.firstName ?: "unknown" // Groovy Elvis
In both cases, if
author.firstName
is
null
, then
firstName
is set to
unknown
. The
author.firstName
fragment of the Elvis operator example is known as the
expression
. If the expression evaluates to
false
or
null
, then the value after the colon is returned.
Safe Navigation/Dereference Operator
The safe navigation/dereference operator (
?.
) is used to avoid null pointer exceptions. Consider the
situation where you have an
Author
object and you want to print the
firstName
. If the
Author
object is
null
when you access the
firstName
property, you will get a
NullPointerException
(see Listing B-37).
Listing B-37. Using the Safe Navigation/Dereference Operator
class Author {
String firstName
String lastName
def printFullName = {
println "${firstName} ${lastName}"
}
}
Author author
println author.firstName
The code in Listing B-37 throws a
NullPointerException
. In Java, you add a
null
check this way:
if (author != null) {
println "Author FirstName = ${author.firstName}"
}
Listing B-38 illustrates how to add the
null
check using the safe navigation/dereference operator
in Groovy.
Listing B-38. Using the Safe Navigation/Dereference Operator
class Author {
String firstName
String lastName
def printFullName = {
println "${firstName} ${lastName}"
}
}
Author author
println "Author FirstName = ${author?.firstName}"