Skip to content

Instantly share code, notes, and snippets.

@radeinla
Created June 28, 2013 18:15
Show Gist options
  • Save radeinla/5886802 to your computer and use it in GitHub Desktop.
Save radeinla/5886802 to your computer and use it in GitHub Desktop.
Newbie at this but why is this printing only the last value of the for loop and not binding each value of the list in the for loop? My expectation was for the last closure statement: obj1 obj2 obj3 but what is actually happening is: obj3 obj3 obj3
List<Integer> list = [1, 2, 3].collect { new Object() }
list.each { println it }
List<Closure> cls = []
for (Object i : list) {
cls << { ->
println i
}
}
cls.each {
it()
}
@ysb33r
Copy link

ysb33r commented Jul 3, 2013

You probably wanted this instead:

List<Integer> list = [1, 2, 3]

list.each { println it }

List<Closure> cls = []

list.each { j->
  cls << { ->
   println j
  }
}

cls.each {
  it()
}

Although the second part can be better written as

def cls = list.collect { j->
    return { -> println j }
}

cls.each {
  it()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment