Archive: June 2018

Groovy Goodness: Preorder And Postorder Tree Traversal

Posted on by  
Hubert Klein Ikkink

The Node class in Groovy has the methods depthFirst and breadthFirst to return a collection of Node objects using either depth or breadth first traversal. Since Groovy 2.5.0 we can specify if we want to use preorder (the default) or postorder traversal. Also the methods now accept a Closure that will be invoked for each visited node. The Closure has the current Node as first argument, the second argument is the tree level of the current node.

In the following example we read some XML and then use depthFirst in several ways to visit the tree of nodes:

Continue reading →

Groovy Goodness: Tuples With Up To 9 Items

Posted on by  
Hubert Klein Ikkink

A tuple is an ordered, immutable list of elements. Groovy supported tuples with one or two elements before Groovy 2.5.0. Since Groovy 2.5.0 we can use tuples with maximal nine items. Groovy added the classes Tuple3 up to Tuple9. The bonus we get compared to an unmodifiable list with elements is that we can use properties like first, second, third, fourth, fifth, sixth, seventh, eighth, ninth to get items at the specified position.

In the following example we use different Tuple classes:

Continue reading →

Groovy Goodness: Creating Extra Method Supporting Named Arguments Using @NamedVariant Annotation

Posted on by  
Hubert Klein Ikkink

Groovy supports named arguments for methods. Actually Groovy collects all named arguments (defined using the name followed by a : and the value) into a Map. The Map must be the first parameter of the method to make it all work. Since Groovy 2.5.0 we can use the @NamedVariant AST transformation annotation to let Groovy create a method where the first parameter is a Map to support named arguments for an existing method. The existing method is still available, but Groovy adds an extra method to our generated class.

By default Groovy will make the first parameters of the original method part of the new method supporting named arguments. If the first parameters is a class type, then the properties of the class can be used as named arguments. We can also explicitly define which parameters of our original method should be named arguments using the annotations @NamedParam and @NamedDelegate. These annotations need to defined for each parameter. The newly created method by the AST transformation invokes the original method.

Continue reading →

Groovy Goodness: Add Map Constructor With Annotation

Posted on by  
Hubert Klein Ikkink

Since the early days of Groovy we can create POGO (Plain Old Groovy Objects) classes that will have a constructor with a Map argument. Groovy adds the constructor automatically in the generated class. We can use named arguments to create an instance of a POGO, because of the Map argument constructor. This only works if we don’t add our own constructor and the properties are not final. Since Groovy 2.5.0 we can use the @MapConstrutor AST transformation annotation to add a constructor with a Map argument. Using the annotation we can have more options to customize the generated constructor. We can for example let Groovy generate the constructor with Map argument and add our own constructor. Also properties can be final and we can still use a constructor with Map argument.

First we look at the default behaviour in Groovy when we create a POGO:

Continue reading →

Groovy Goodness: Implement Interface And Abstract Methods Automatically

Posted on by  
Hubert Klein Ikkink

A lot of new AST transformation annotations are added in Groovy 2.5.0. One of them is the @AutoImplement annotation. If we apply this annotation to our class dummy implementations for abstract methods in superclasses or methods in implemented interfaces are created. This can be useful to have something in place and then gradually write real implementations for the abstract or interface methods. The transformation will not alter any method that is already implemented by custom code.

When we apply the @AutoImplement annotation the default implementation for an abstract method from a superclass or method from a interface is simple. If the method has a return type the default value of that return type is returned. For example false for a boolean and null for an object type. But the @AutoImplement annotation has some attributes we can use to change the default implementation. We can set the exception attribute and assign a exception type. The implementation of the methods is than to throw that exception when the method is invoked. With the optional message attribute we can set the exception message. Finally we can use the code attribute to define a Closure with statements that will be called as the implementation of abstract and interface methods.

Continue reading →

Groovy Goodness: Customizing JSON Output

Posted on by  
Hubert Klein Ikkink

Groovy 2.5.0 adds the possibility to customize JSON output via a JsonGenerator instance. The easiest way to turn an object into a JSON string value is via JsonOutput.toJson. This method uses a default JsonGenerator with sensible defaults for JSON output. But we can customize this generator and create JSON output using the custom generator. To create a custom generator we use a builder accessible via JsonGenerator.Options. Via a fluent API we can for example ignore fields with null values in the output, change the date format for dates and ignore fields by their name or type of the value. And we can add a custom converter for types via either an implementation of the conversion as Closure or implementation of the JsonGenerator.Converter interface. To get the JSON string we simple invoke the toJson method of our generator.

In the following example Groovy code we have a Map with data and we want to convert it to JSON. First we use the default generator and then we create our own to customize the JSON output:

Continue reading →

Groovy Goodness: Remove Last Item From List Using RemoveLast Method (And Pop/Push Methods Reimplemented)

Posted on by  
Hubert Klein Ikkink

Versions of Groovy before 2.5.0 implemented pop and push methods for the List class for items at the end of a List object. The pop method removed the last item of a List and push added a item to the List. Groovy 2.5.0 reimplemented the methods so they now work on the first item of a List instance. To remove an item from the end of the list we can use the newly added method removeLast.

In the following example Groovy code we use the removeLast and add methods to remove and add items to the end of the list. And with the pop and push methods we remove and add items to the beginnen of the list:

Continue reading →

Groovy Goodness: Getting All Init And Tail Values Recursively

Posted on by  
Hubert Klein Ikkink

For a long time we could get the tail or init valuesfor a collection. Groovy 2.5.0 adds the methods inits and tails for Iterable objects. These methods return a List with List values where the first element is the original collection and the next is the result of init or tail on the previous element. This is repeated until the result of init or tail is an empty List.

In the next example script we have a original collection of letters. We first run the init and tail methods (without the s). Next we look at the result of invoking inits and tails:

Continue reading →

Groovy Goodness: Intersect Collections With Custom Comparator

Posted on by  
Hubert Klein Ikkink

In a previous postwe learned about the intersect method added to collections in Groovy. Since Groovy 2.5.0 we can supply a custom Comparator to the intersect method to define our own rules for the intersection.

In the following example we first apply the intersect method with the default Comparator. Then we create a new Comparator using a closure where we check if the value is in both collections and if the value starts with the letter M:

Continue reading →

Groovy Goodness: Easy Object Creation With Tap Method

Posted on by  
Hubert Klein Ikkink

Groovy 2.5.0 adds the tap method to all objects and changes the method signature of the with method. In a previous post we already learned about the with method. In Groovy 2.5.0 we can add an extra boolean argument to the with method. If the value is false (is default) the with method must return the same value as what the closure invocation returns. If the value is true the object instance on which the with method is invoked is returned. The new tap method is an alias for with(true), so it will always return the object instance.

In the first example we use the tap method to create a new Sample object and set property values and invoke methods of the Sample class:

Continue reading →

shadow-left