| |
| 1 Differences from Java |
| |
| Groovy tries to be as natural as possible for Java developers. |
| We've tried to follow the principle of least surprise when designing Groovy, |
| particularly for developers learning Groovy who've come from a Java background. |
| |
| Here we list all the major differences between Java and Groovy. |
| |
| 1.1 Common gotchas |
| |
| Here we list the common things you might trip over if you're a Java developer starting to use Groovy |
| * == means equals on all types and === means identity compare. In java there's a wierd part of the syntax where == means equality for primitive types and == means identity for objects. Since we're using autoboxing this would be very confusing for Java developers (since x == 5 would be mostly false if x was 5 :). So for simplicity == means equals() in Groovy |
| * if you want to use the neat syntax sugar for passing closures into methods or using GroovyMarkup - be aware that the { must be on the same line. |
| |
| For example the following is valid groovy |
| |
| {code:groovy} |
| [1, 2, 3].each { println it } |
| {code} |
| |
| However if you want to specify the { on a separate line then you must use the more verbose parentheses version like this |
| |
| {code:groovy} |
| [1, 2, 3].each ( |
| { println it } |
| ) |
| {code} |
| |
| i.e. you cannot do this |
| |
| {code:badGroovy} |
| [1, 2, 3].each |
| { |
| println it |
| } |
| {code} |
| |
| As the above is interpreted as the use of the 'each' property and then the creation of a closure; which is not passed into an each() method call. |
| |
| |
| 1.1 Things to be aware of |
| |
| * semicolon is optional. Use then if you like (though you must use them to put several statements on one line). |
| * the return keyword is optional |
| * you can use the __this__ keyword inside static methods (which refers to this class) |
| * things are public by default. There's no need to use the public modifier on classes or methods though you can if you like |
| * protected in Groovy is the equivalent of both package-protected and protected in Java. i.e. you can have friends in the same package - or derived classes can also see protected members. |
| |
| 1.1 New features added to Groovy not available in Java |
| |
| * {link:closures|closures.html} |
| * native {link:syntax|collections.html} for lists and maps |
| * {link:GroovyMarkup|markup.html} and GPath support |
| * native support for {link:regular expressions|regex.html} |
| * polymorphic {link:iteration|loops.html} and powerful {link:switch statement|branches.html} |
| * dynamic and static typing is supported - so you can omit the type declarations on methods, fields and variables |
| * you cam embed expressions inside {link:strings|strings.html} |
| * lots of new helper methods added to the {link:JDK|groovy-jdk.html} |
| * simpler syntax for writing {link:beans|beans.html} for both properties and adding event listeners |