Before playing with the examples you'll find below, you shoud first :
- Installing Groovy
- Embedding Groovy
- Command Line : Groovy can be launched in shell script mode
- Compiling Groovy : Groovy can be launched as any java program
- Bean Scripting Framework : embedding groovy in java code
Your First Groovy
To run it from command line
Groovy classes compile down to Java bytecode and so there's a 1-1 mapping between a Groovy class and a Java class.
Indeed each Groovy class can be used inside normal Java code - since it is a Java class too.
Probably the easiest way to get groovy is to try working with collections. In Groovy List (java.util.List) and Map (java.util.Map) are both first class objects in the syntax. So to create a List of objects you can do the following...
Notice that everything is an object (or that auto-boxing takes place when working with numbers). To create maps...
Iterating over collections is easy...
Once you have some collections you can then use some of the new collection helper methods or try working with closures...
Working with closures
Closures are similar to Java's inner classes, except they are a single method which is invokable, with arbitrary parameters. A closure can have as many parameters as you wish...
If no parameter(s) is(are) specified before -> symbol then a default named parameter, called 'it' can be used. e.g.
Using closures allows us to process collections (arrays, maps, strings, files, SQL connections and so forth) in a clean way. e.g
Note: If a given closure is the last parameter of a method, its definition can reside outside of the parentheses. Thus the following code is valid:
Here are a number of helper methods available on collections & strings...
iterate via a closure
collect the return value of calling a closure on each item in a collection
finds first item matching closure predicate
finds all items matching closure predicate
allows you to pass a value into the first iteration and then pass the result of that iteration into the next iteration and so on. This is ideal for counting and other forms of processing
In addition there's 2 new methods for doing boolean logic on some collection...
returns true if all items match the closure predicate
returns true if any item match the closure predicate
Other helper methods include:
max / min
returns the max/min values of the collection - for Comparable objects
concatenates the values of the collection together with a string value
Also the 'yield' style of creating iterators, available in Python and Ruby via the yield statement, is available. The only difference is rather than using a yield statement, we're just using closures.
The use of Closure in the method prototype is optional. If we have syntax sugar for invoking closures as if they are method calls, then the generator method could look even more like the python/ruby equivalent. Especially if parentheses are optional...