When to Use the Safe Dereferencing ?. Operator in Groovy
The NullPointerException
is the bane of Groovy (and Java) developers! What if an operator existed that might mitigate the occurrences of this dreaded exception?
An operator does exist in Groovy to help us out: the safe dereferencing operator, ?.
. In this topic you will find out when to use this operator.
To learn when to use the safe dereferencing operator in Groovy follow these 6 steps:
- Open your text editor and type in the following lines of Groovy code:
You can probably see the problem right off the bat: the string variable has not been initialized! Of course, this is a very simple program but in the real world programs are much more complicated and you might not be aware that a certain string (or an object in general) is initialized . We will go ahead then and run this program to witness the exception first hand.
def fullName // The following line will cause a NullPointerException println "Display length of fullName: ${fullName.length()}"
- Save your file as
SafeDereferencing.groovy
. - In the command prompt, type in the command to interpret and run your script:
The output displays aNullPointerException
because we are attempting to use a property (length
) on a string that was never initialized. - Return to your editing session and change
fullName.
tofullName?.
on theprintln
statement as shown below:You can remove the comment too because now the program will not terminate with adef fullName // The following line will cause a NullPointerException println "Display length of fullName: ${fullName?.length()}"
NullPointerException
. In general, use the safe dereferencing operator any time you are attempting to access a method of an object unless you are certain the object has been initialized! - Save your changes.
- In the command prompt, type in the command to interpret and run your script:
The output displays the value of the length asnull
and this verifies that aNullPointerException
was NOT thrown because of the safe dereferencing operator.