Groovy Inline Closures

Consider the following closure sum and it's use in inject method.

def numbers = [1, 2, 3, 4, 5, 6, 7]

def sum = { number1, number2 ->
    number1 + number2

println numbers.inject(0, sum) // 28
If you are not familiar with Groovy closures, this post has the details.

In the above code, we have created a closure (a block of code) and assigned it to the name(variable) sum, effectively naming the closure. Alternatively, we can directly pass the anonymous code block as an argument to a function, without assigning a name to it.

One of the ways of arriving such a code is by applying the inline refactoring technique. I use IntelliJ IDEA for working with Groovy code. In this IDE, I can apply inline refactoring by selecting "inline" option from the "Refactor" menu. If you are inlining regularly, I highly recommend using the corresponding keyboard shortcut. We are left with the following code after the refactoring.

def numbers = [1, 2, 3, 4, 5, 6, 7]

println numbers.inject(0, { number1, number2 ->
    number1 + number2
}) // 28

Looking at the code, I would say that is not one of the most readable code I have come across. Luckily, the designers of Groovy language had already thought through this and came up with the following solution.

Whenever the last argument to a function is a closure, you are allowed to write the inline closure outside the closing parentheses. Hence the above code can also be written as follows.

def numbers = [1, 2, 3, 4, 5, 6, 7]

println numbers.inject(0) { number1, number2 ->
    number1 + number2
} // 28

Pause for a while and decide for yourself - which version do you think is more readable?

Show Comments