Programming Grails - Cdn.oreilly.com
Programming Grails - Cdn.oreilly.com
Programming Grails - Cdn.oreilly.com
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
or you could just skip the whole for loop and use times:<br />
someCalculation().times {<br />
...<br />
}<br />
or a range with a loop, if you need access to the loop variable:<br />
for (i in 0..someCalculation()-1) {<br />
...<br />
}<br />
Annotations<br />
Annotation values that have array types use a different syntax in Groovy than Java. In<br />
Java, you use { and } to define multivalued attributes:<br />
@Secured({'ROLE_ADMIN', 'ROLE_FINANCE_ADMIN', 'ROLE_SUPERADMIN'})<br />
but because these are used to define closures in Groovy, you must use [ and ] instead:<br />
@Secured(['ROLE_ADMIN', 'ROLE_FINANCE_ADMIN', 'ROLE_SUPERADMIN'])<br />
Groovy Equality<br />
The previous examples will cause <strong>com</strong>pilation errors if you rename a .java class<br />
to .groovy and try to <strong>com</strong>pile it, or copy/paste Java code into an existing Groovy class.<br />
But checking for object equality actually works differently in Groovy.<br />
In Java, == is mostly used for <strong>com</strong>paring numbers and other primitives, because <strong>com</strong>‐<br />
paring objects with == just <strong>com</strong>pares object references but not the data in the instances.<br />
We use the equals method to test if two objects are equivalent and can be considered<br />
equal even though they’re not the same instances. But it’s rare to need the == object<br />
<strong>com</strong>parison, so Groovy overloads it to call equals (or <strong>com</strong>pareTo, if the objects imple‐<br />
ment Comparable). And, if you do need to check that two references are the same object,<br />
use the is method—e.g., foo.is(bar).<br />
Groovy’s == overload is convenient and avoids having to check for null values, but be‐<br />
cause it works differently than the Java operator, you might want to consider not using<br />
it. It’s simple enough to replace x == y with x?.equals(y), which isn’t that many more<br />
characters and is still null-safe. Working with both Java and Groovy will keep you from<br />
introducing subtle bugs in your Java code. (I’m speaking from experience here….)<br />
Multimethod Dispatch<br />
Overloaded method selection is another runtime difference between Java and Groovy.<br />
Java’s type checking is stricter, so it uses the <strong>com</strong>pilation type of a variable to choose<br />
18 | Chapter 1: Introduction to Groovy