04.07.2013 Views

Programming Grails - Cdn.oreilly.com

Programming Grails - Cdn.oreilly.com

Programming Grails - Cdn.oreilly.com

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The output from the above code is:<br />

static_propertyMissing foo<br />

static_methodMissing foo<br />

null<br />

static_propertyMissing bar<br />

null<br />

$static_methodMissing works slightly differently from methodMissing in that if there’s<br />

no method with the specified name, it looks for a closure property with that name to<br />

invoke as if it were a method. This results in a message about a missing foo property<br />

and a missing foo method.<br />

Operators<br />

Groovy adds several operators to the standard set of Java operators.<br />

Null-Safe Dereference<br />

The most <strong>com</strong>monly used is the null-safe dereference operator, ?., which lets you avoid<br />

a NullPointerException when calling a method or accessing a property on a null object.<br />

It’s especially useful in a chain of such accesses where a null value could occur at some<br />

point in the chain.<br />

For example, you can safely call:<br />

String name = person?.organization?.parent?.name<br />

and if person, person.organization, or organization.parent are null, then null is<br />

returned as the expression value. The Java alternative is a lot more verbose:<br />

Elvis<br />

String name = null;<br />

if (person != null) {<br />

if (person.getOrganization() != null) {<br />

if (person.getOrganization().getParent() != null) {<br />

name = person.getOrganization().getParent().getName();<br />

}<br />

}<br />

}<br />

The Elvis operator, ?:, lets you condense ternary expressions; these two are equivalent:<br />

and:<br />

String name = person.name ?: defaultName<br />

String name = person.name ? person.name : defaultName<br />

26 | Chapter 1: Introduction to Groovy

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!