Simplified Syntax
Groovy also provides simplified syntax so that the same logic in Java can be implemented in Groovy with
less code. Some of the basic syntax is as follows:
A semicolon is not required for ending a statement.
In methods, the return keyword is optional.
All methods and classes are public by default. So, unless required, you don't need
to declare the public keyword for method declaration.
Within a class, Groovy will automatically generate the getter/setter methods for
the declared properties. So in a Groovy class, you just need to declare the type and
name (for example, String firstName or def firstName), and you can access the
properties in any other Groovy/Java classes by using the getter/setter methods
automatically. In addition, you can also simply access the property without the
get/set prefix (for example, contact.firstName = 'Clarence'). Groovy will handle
them for you intelligently.
Groovy also provides simplified syntax and many useful methods to the Java Collection API. Listing
22-4 shows some of the commonly used Groovy operations for list manipulation (the file name is
CollectionSample.groovy).
Listing 22-4. Groovy for Managing List
package com.apress.prospring3.ch22.groovy
// Define a list as an ArrayList
def list = ['This', 'is', 'Clarence']
assert list.size() == 3
assert list.class == ArrayList
// Reverse a list
assert list.reverse() == ['Clarence', 'is', 'This']
// Sort a list by string size
assert list.sort{ it.size() } == ['is', 'This', 'Clarence']
// Sub list
assert list[0..1] == ['is', 'This']
// Use << for append item
assert list << 'Ho' == ['is', 'This', 'Clarence', 'Ho']
The listing shows only a very small portion of the features that Groovy offers. For a more detailed
description, please refer to the Groovy online documentation at http://groovy.codehaus.org/JN1015-
Collections.
Closure
One of the most important features that Groovy adds to Java is the support of closures. A closure allows a
piece of code to be wrapped as an object and to be passed freely within the application. Closure is a very
powerful feature that enables smart and dynamic behavior. The addition of closure support to the Java
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home