Groovy and the safe dereference operator

When going through view code generated by Grails I noticed heavy use of the question mark operator when referencing properties. After browsing around I discovered that it is called the ‘safe dereference operator’

Sounds more complex then it is, it just makes sure that consequent methodcalls are only executed when the object on which it is called actually exists:

[groovy]
user?.email?.encodeAsHTML()
[/groovy]

In the case above the ‘email’ property will only get read when the ‘user’ object actually exists and the ‘encodeAsHTML()’ will only get called when the ‘email’ property actually has a value. Cool!

This entry was posted in grails, groovy. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>