[
https://issues.apache.org/jira/browse/GROOVY-11792?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18032950#comment-18032950
]
Daniel Sun commented on GROOVY-11792:
-------------------------------------
It seems closures reference the same variable {{n}}, and do not copy the value.
So we can define a variable in the loop to workaround the issue.
{code:java}
import java.util.function.Supplier
def numbers = [1, 2, 3]
List suppliers = []
for (var ln : numbers) {
var n = ln
println "v: ${n}"
Supplier s = () -> {
def r = n * n
println "$n: $r"
return r
}
suppliers << s
}
println "Result: ${suppliers.sum(e -> e.get())}"
{code}
yields the correct result:
{code:java}
v: 1
v: 2
v: 3
1: 1
2: 4
3: 9
Result: 14
{code}
> Incorrect captured variable in closure
> --------------------------------------
>
> Key: GROOVY-11792
> URL: https://issues.apache.org/jira/browse/GROOVY-11792
> Project: Groovy
> Issue Type: Bug
> Affects Versions: 2.5.23, 3.0.25, 4.0.29, 5.0.2
> Reporter: Daniel Sun
> Priority: Major
>
> Expect 14(1+4+9), but get 27(9+9+9)
> {code:java}
> import java.util.function.Supplier
> def numbers = [1, 2, 3]
> List suppliers = []
> for (n in numbers) {
> println "v: ${n}"
> Supplier s = {
> def r = n * n
> println "$n: $r"
> return r
> }
> suppliers << s
> }
> println "Result: ${suppliers.sum({e -> e.get()})}"
> {code}
> yields:
> {code:java}
> v: 1
> v: 2
> v: 3
> 3: 9
> 3: 9
> 3: 9
> Result: 27
> {code}
--
This message was sent by Atlassian Jira
(v8.20.10#820010)