Groovy Goodness: Easy Object Creation With Tap Method

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:

In the following example we use the with method to demonstrate the differences for several invocations using different argument values:

A good use case for using the with method is to transform an object to another type using values from the object. In the next example we use values from a Sample objects to create a new String:

Written with Groovy 2.5.0.

Original post

This entry was posted in Coding, Groovy and tagged by mrhaki. Bookmark the permalink.

About mrhaki

My name is Hubert A. Klein Ikkink also known as mrhaki. I work at the great IT company JDriven. Here I work on projects with Groovy & Grails, Gradle and Spring. At JDriven we focus on SpringSource technologies. All colleagues want to learn new technologies, support craftmanship and are very eager to learn. This is truly a great environment to work in. You can contact me via Google+ or @mrhaki.

Leave a Reply

Your email address will not be published. Required fields are marked *