开发者

@Typed annotation stops Groovy code compiling

开发者 https://www.devze.com 2023-03-25 05:08 出处:网络
Why does this Groovy code... def mt(){ def i= 0 def c= {i++} } ...compile, but 开发者_StackOverflow中文版this Groovy code...

Why does this Groovy code...

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

...compile, but 开发者_StackOverflow中文版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++}
         ^


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


This issue posted to the google code tracker states:

This is by design.

And links to a message on the user group, which states:

Yes, this is one of most significant differences with standard Groovy. In Groovy++ shared closure variables are always final.

I cannot see how you could rewrite that code you have in a groovypp friendly way, so I guess you would either need to refactor the code to do it another way, or else not declare it as @Typed

Edit: I guess you could encapsulate the behaviour in a class, and return a method handle to a member function

0

精彩评论

暂无评论...
验证码 换一张
取 消