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

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.

In the following example we use @NamedVariant for the ConferenceMaker.copy method:

In the next example we use @NamedParam to define the parameters that need to be used as named arguments. We can use the attribute required to indicate the named argument must be provided otherwise an error is thrown:

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 *