More work on Life.groovy


According to “Groovy in Action” lists of lists are the correct way to do multidimensional arrays in Groovy, so I reckon I will try that now – as well as making some better use of some of the other language features, such as better use of ranges, that I noticed could be done.

A bit of a Groovy gotcha


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.