In Groovy, the inject() method is one of the cumulative methods that allows us to add (or inject) new functionality into any object that implements the inject() method. In the case of a Collection, we can apply a closure to a collection of objects uniformly and then collate the results into a single value. The first parameter to the inject() method is the initial value of the cumulation and the second parameter is the closure.
In this example, we will take a List of Strings as a parameter and output the values of those strings delimited by commas. I have used this functionality to append a list of values to a REST query string and, if you modify it a bit, I've used it to include values into a SQL statement as part of a IN clause. Here is the code to do this:
public String convertToCSV( List<String> list ) {
if (list == null) {
return ""
}
return list.inject( '' ) { result, item ->
result + ( result && item ? ',' : '' ) + ( item ? "${item.trim()}" : '' )
}
}
assert convertToCSV( null ) == ""
assert convertToCSV( ["aaa", "bbb ", null, " ccc "] ) == "aaa,bbb,ccc"
In this example, the first parameter to the inject() method is a zero length string, which means that when processing the first element of the list, result is also a zero length string. This resolves to false in the first ternary evaluation which is why we don't get a comma at the beginning of the string. With each consecutive iteration through the elements of the list, result becomes the concatenation of itself, a comma and then the next item until we reach the last item in the list.
The advantage of this approach is that you don't need a variable outside of a looping construct to hold the concatenated String result. The implication being that this can lead to side effects in your code. With the inject() approach, this behavior is injected and the collection collates the result of the calls to the closure for you. The downside of this approach can be readability. But with some experience, it becomes easier to read and understand, and I hope this example helps you obtain that goal.