- Bazhidar Batsov has a great post on Groovy
- Groovy has a great Getting Started Guideline
Installation and Getting Started
- Download the binary distribution and unpack it into some folder (i.e. /groovy-1.8.0)
- (Optional) Create a symbolic link to the groovy directory and I name it "/groovy".
- Set your GROOVY_HOME environment
if you do a "ls -l /groovy" you will get the following:
In my application I do the following (MacBook Pro using TextMate):
To make sure that you have the latest installation, do the following:
Most people I know work with Eclipse. Groovy has a plugin for Eclipse and a tutorial to upgrade the Groovy version inside your IDE.
SQL and Groovy:
Which will return the following:
-- Marcelo --
-- Antonio --
-- Jorge Luis --
-- Nestor --
In the new Groovy 1.8, there is a feature for pagination:
Where the first two states the starting point and the next two states the max record to fetch.
Tests are perfect for Groovy. You can use the latest JUnit to run all the unit test cases as do in Java. Below I will be using some of the example using JUnit test:
Closures and Arrays/List:
Different people use Groovy in different ways, but everyone agrees that the collection API for Groovy is very powerful. Below are more examples of using List or Arrays along with closures:
As you can see, the each is a closure in Groovy and it iterates through the list. The output is the following:
Closure composition is to be able to combine closure with one another. In some cases you want to combine two type of functions. For example:
Groovy used to have error when using closures in recursive algorithms. They were able to resolve this issue with trampoline. Here is an example of using the factorial function.
Memoize is a very interesting tool for Groovy. From the Groovy's documentation:
The return values for a given set of Closure parameter values are kept in a cache, for those memoized Closures. That way, if you have an expensive computation to make that takes seconds, you can put the return value in cache, so that the next execution with the same parameter will return the same result – again, we assume results of an invocation are the same given the same set of parameter values.
There are three forms of memoize functions:
- the standard memoize() which caches all the invocations
- memoizeAtMost(max) call which caches a maximum number of invocation
- memoizeAtLeast(min) call which keeps at least a certain number of invocation results
- and memoizeBetween(min, max) which keeps a range results (between a minimum and a maximum)
Here is an example:
Fri Jun 24 13:29:15 EDT 2011
Fri Jun 24 13:29:16 EDT 2011
Fri Jun 24 13:29:16 EDT 2011
Fri Jun 24 13:29:17 EDT 2011
Maps and Default Value:
Maps now can have a default value (similar to Ruby). In the case below, if we needed to count the frequency of words in a sentence, we can start a map and store the words and the counter. By configuring the default counter, all the words will have a 0
Groove on brother!