[
https://issues.apache.org/jira/browse/GROOVY-8826?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
]
Daniel Sun reassigned GROOVY-8826:
----------------------------------
Fix Version/s: 7.0.0-alpha-1
Assignee: Daniel Sun
> Captured loop variables have surprising and Java-incompatible behavior
> ----------------------------------------------------------------------
>
> Key: GROOVY-8826
> URL: https://issues.apache.org/jira/browse/GROOVY-8826
> Project: Groovy
> Issue Type: Bug
> Affects Versions: 3.0.0-alpha-3
> Reporter: Роман Донченко
> Assignee: Daniel Sun
> Priority: Major
> Fix For: 7.0.0-alpha-1
>
>
> Consider this source:
> {code:java}
> import java.util.ArrayList;
> import java.util.Arrays;
> public class Test {
> public static void main(String... args) {
> ArrayList<Runnable> closures = new ArrayList<>();
> for (int i: new int[] {1, 2})
> closures.add(() -> System.out.println(i));
> for (Runnable closure: closures)
> closure.run();
> }
> }
> {code}
> If it's compiled as Java, the output is:
> {code}
> 1
> 2
> {code}
> But if it's compiled as Groovy, the output is:
> {code}
> 2
> 2
> {code}
> In other words, in Java each iteration gets a unique instance of the {{i}}
> variable, which is captured in the corresponding closure, while in Groovy,
> only one {{i}} variable exists and is captured into both closures. IMO, the
> Groovy behavior is significantly less useful, and it would be nice if in 3.0
> it was changed to match Java.
> Groovy also exhibits the same behavior with Groovy closures and
> {{for(...in...)}} loops. I just used Java-compatible syntax for this example
> in order to contrast Groovy and Java.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)