Programming Grails - Cdn.oreilly.com
Programming Grails - Cdn.oreilly.com
Programming Grails - Cdn.oreilly.com
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
with:<br />
String s = someMethod(...)<br />
if (s) { ... }<br />
Semicolons<br />
Semicolons are for the most part unnecessary in Groovy, the exception being the tra‐<br />
ditional for loop (although you’ll most likely prefer the semicolon-free Groovy for/in<br />
version). Also, if you want to have multiple statements on one line, you still need to<br />
delimit them with semicolons.<br />
Optional Return<br />
You can omit the return keyword in a method or closure, because Groovy treats the<br />
last expression value as the return value if you don’t use return.<br />
Scope<br />
Scope modifiers are often omitted in Groovy because the default scope is public. You<br />
can still define private or protected fields and methods. Because package scope is the<br />
default in Java and there’s no keyword for that, Groovy added the groovy.trans<br />
form.PackageScope annotation in version 1.8 for classes, methods, and fields.<br />
Parentheses<br />
You can often omit parentheses in method calls. This is only true if the method has<br />
arguments, because otherwise the call would look like property access. So, for example,<br />
all but the last of these are valid:<br />
println("Using parentheses because I can")<br />
println "Omitting parentheses because I can"<br />
println()<br />
println // not valid; looks like property access<br />
// for a nonexistent getPrintln() method<br />
You can’t omit parentheses from the right side of an assignment, however:<br />
int sum = MathUtils.add(2, 2) // ok<br />
int product = MathUtils.multiply 2, 2 // invalid, doesn't <strong>com</strong>pile<br />
Default Imports<br />
Another space saver is the extended list of default imports. Java automatically imports<br />
everything from the java.lang package, and Groovy extends this to include java.io.*,<br />
java.net.*, java.util.*, groovy.lang.*, and groovy.util.*, as well as the<br />
java.math.BigDecimal and java.math.BigInteger classes.<br />
16 | Chapter 1: Introduction to Groovy