Monday morning, while doing pair programming with my boss at work, we encountered an interesting behavior in Groovy. It’s not a bug, but I was surprised enough to share it with you.
Let’s define two arrays:
def a = [1, 2, 3] def b = [4, 5, 6]
We wanted to add the elements from “b” to “a”. Groovy overloads the “<<” operator on arrays, allowing you to push items into an array. Naturally, our first instinct was to use that. However, it didn’t work.
a << b println a [1, 2, 3, [4, 5, 6]]
The reason is that an array in Groovy is a heterogenous list of objects, and objects of differents types can be put in the same array. In our case, Groovy pushed the array “b” (its reference) into “a”.
We quickly realized our mistake. Multiples solutions exist to solve our problem. We took a loop-based approach, like so, iterating through “b” and pushing every element into “a”.
a = [1, 2, 3] b.each { a << it} println a [1, 2, 3, 4, 5, 6]
We could have used the “addAll()” method, inherited from Java, which pushes all the elements from one array into another.
a = [1, 2, 3] a.addAll(b) println a [1, 2, 3, 4, 5, 6]
A more elegant solution, though, would have been to use operator overloading. By using the “+=” operator, the elements of “b” will be appended to “a”.
a = [1, 2, 3] a += b println a [1, 2, 3, 4, 5, 6]
As closing words, if you want to quickly test some Groovy code, head over to the Groovy web console, which runs a Groovy console on Google App Engine. In it, you can write Groovy code and execute it, and the results will be displayed on the Web page.