A very useful feature in Groovy is the use of named arguments. Instead of a list of arguments for a method or constructor we can use a Map argument. If the argument is the first in the list of arguments then Groovy allows use to use named arguments when we invoke the method or constructor. This means all key/value arguments are gathered together and assigned to the Map argument. Inside our method or constructor we can then access the Map argument and get the values for the keys. This leads to better readable code and that is very useful. IntelliJ IDEA has a Groovy intention to turn method parameters into a Map parameter for named arguments with a few mouse clicks.

Suppose we have the following source code with a simple method definition, 2 arguments, and the invocation of the method:

Now we activate the Groovy intentions (for me it is Alt+Enter or try Shift+Shift and type Show intentions actions) while we place the cursor on the parameter greeting. We select the option Convert parameter to map entry:

IntelliJ IDEA opens a new dialog. Here we can choose to create a new Map parameter for named arguments. If our method would have a Map argument already we can re-use it. We can let IDEA add the Map type or leave it out. Finally we can change the name of the parameter. In our example we have changed it to conf:

When we click the OK button we see our source code has changed. Not only the method signature of the simple method, but also the invocation has changed:

We can re-apply the same intention for the username parameter and we get the following code:

Written with IntelliJ IDEA CE 14.1.4.

Original article