Search code examples
groovygroovy++

@Typed annotation stops Groovy code compiling


Why does this Groovy code...

def mt(){
  def i= 0
  def c= {i++}
}

...compile, but this Groovy code...

@Typed def mt(){
  def i= 0
  def c= {i++}
}

...not compile with error...

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:  
C:\Users\gavin\Documents\Personal\Groovy\otherRun.groovy: 5: 
Cannot modify final field otherRun$mt$1.i @ line 5, column 11.  
 def c= {i++}
         ^

Solution

  • You can work around the restriction via the @Field annotation, like so:

    @Typed def mt(){
        @Field def i = 0
        def c = {i++}
    }
    
    assert mt().call() == 0
    assert mt().call() == 1