Groovy++ Goodies (1) – Closure Level Fields

Groovy++ allows you to declare closure level fields using its new @Field annotation.

In core groovy, if you need to remember some state across multiple calls to the same closure instance, you need to do it using variable declared outside the closure scope. So, I see this Groovy++ feature as a useful goodie.

Below is some sample code to demonstrate the use of closure level fields:

@Typed void squares() {
    (1..20).each {
        @Field boolean lastOneSqaure = false
        @Field int which = 0
        
        if(lastOneSqaure) println "$it) Last number($which) was a square"
        
        double d = Math.sqrt(it)
        if((d - ((int) d) == 0)) {
            lastOneSqaure = true
            which = it
        } else {
            lastOneSqaure = false
        }
    }
}

squares()

The above code correctly outputs

2) Last number(1) was a square
5) Last number(4) was a square
10) Last number(9) was a square
17) Last number(16) was a square

The groovy++ compiler makes sure that the variables marked with @Field are declared as fields in the closure class and not as local variables – allowing you to preserve state across multiple invocations to a particular closure instance without needing any out-of-closure-scope assistance.

Advertisements