You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@groovy.apache.org by "Paul King (JIRA)" <ji...@apache.org> on 2015/05/01 05:31:06 UTC

[jira] [Commented] (GROOVY-7409) Closure reference a wrong object when is defining inside an iterator

    [ https://issues.apache.org/jira/browse/GROOVY-7409?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=14522718#comment-14522718 ] 

Paul King commented on GROOVY-7409:
-----------------------------------

The joy of closures!

Try this variant (see if the NPE helps explain what is going on):
{code}
for( def item : list ) {
  hooks.add { item.m() }
  item = null
}
{code}
And for a corrected version:
{code}
for( def item : list ) {
  def x = item
  hooks.add { x.m() }
}
{code}


> Closure reference a wrong object when is defining inside an iterator 
> ---------------------------------------------------------------------
>
>                 Key: GROOVY-7409
>                 URL: https://issues.apache.org/jira/browse/GROOVY-7409
>             Project: Groovy
>          Issue Type: Bug
>          Components: groovy-runtime
>    Affects Versions: 2.3.11, 2.4.3
>            Reporter: paolo di tommaso
>
> A closure defined inside an iterator containing a reference to the iterating item resolves a wrong object instance. 
> To reproduce the error take in consideration the following snippet: 
> {code}
> interface Alpha {
>   abstract void m()
> }
> class Foo implements Alpha { 
>   void m() { println 'foo' }
> }
> class Bar implements Alpha { 
>   void m() { println 'bar' }
> }
> List list = [new Foo(), new Bar()]
> def hooks = []
> for( def item : list ) {
>   hooks.add { item.m() }
> }
> hooks.each { it.call() }
> {code}
> It prints 
> {code}
> bar
> bar
> {code}
> Replacing the `for` iterator which a for( int i=0; etc ) prints correctly: 
> {code}
> foo
> bar
> {code}



--
This message was sent by Atlassian JIRA
(v6.3.4#6332)