Archive for April, 2011
When we write recursive code we might get a stack overflow exception, because calls are placed on the stack to be resolved. Since Groovy 1.8 we can use the trampoline capability of closures to overcome this problem.
Groovy already has a lot of ways to define a String value, and with Groovy 1.8 we have another one: the dollar slashy String. This is closely related to the slashy String definition we already knew (which also can be multi-line by the way, added in Groovy 1.8), but with different escaping rules. We don’t have to escape a slash if we use the dollar slashy String format, which we would have to do otherwise.
There are a lot of new features in Groovy 1.8. One of them is the possibility to compose a new closure by chaining two other closures together. We use the leftShift and rightShift operators (<< and >>) to combine multiple closures to create a new closure.
Since Groovy 1.8 we can use the
equals() method to compare the contents of two
Set collections. The two sets are equals if they have the same size and all elements are in both sets.
Since Groovy 1.8 we can create a new list from two lists, where the second list is ‘inserted’ at a specified index position in the first list. The original lists are not changed: the result is a new list. Groovy also adds the
addAll() method to List objects (since Groovy 1.7.2), but then the original list object is changed.
Since Groovy 1.8 we can convert an array or collection to a Set with only the unique elements of the original array or collection. We use the
toSet() method to do this.
Groovy adds the
toSet() method to the
String class in version 1.8. With this method we get a Set of unique String values from the original String value.
There are a lot of new bytecode generation annotation in Groovy 1.8. One of them is the
@EqualsAndHashCode annotation. With this annotation an
hashCode() method is generated for a class. The
hashCode() method is implemented using Groovy’s
org.codehaus.groovy.util.HashCodeHelper (following an algorithm from the book Effective Java). The
equals() method looks at all the single properties of a class to see of both objects are the same.
Groovy 1.8 adds the
@TupleConstructor annotation. With this annotation we can automatically create a tuple constructor at compile time. So the constructor can be found in the compiled class. For each property in the class a parameter in the constructor is created with a default value. The order of the properties defined in the class also defines the order of parameters in the constructor. Because the parameters have default values we can use Groovy syntax and leave parameters at the end of the parameter list out when we use the constructor.