A bit of a Groovy gotcha

Standard

This tripped me up this afternoon so it might be useful to write about it…

I have been tidying up my classwork exercise Groovy, seeking to eliminate the repeated redefinition of constants – so I defined something like this:

enum ExerciseConstants {
FIRST(1)
SECOND(2)
THIRD(3)
final int value
ExerciseConstants(int value) {
this.value = value
}
}

Then I wrote some code like this:

ExceriseConstants.each {
int x = it.getValue()
ExerciseConstants.each {
int y = it.getValue()
if (foo(x,y))
return true
}
}
return false

But while foo(x,y) would surely be true only false was ever returned.

The reason is that .each (which is not supposed to be broken out of in this way) sees that return and all that happens is that control is returned to the outer closure.

In these circumstances it is much better to use code like this:

for (i in ExerciseConstants) {
for (j in ExerciseConstants) {
if foo(i.getValue(), j.getValue()) == true
return true
}
}
return false

Which works as (I) expected.

One thought on “A bit of a Groovy gotcha

  1. Pingback: Groovydoc issue | cartesian product

Comments are closed.