Groovy web console

subscribe to the feed Subscribe
to this
site

closure-variables

Published 1 month ago by dnusbaum
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def closures1 = [];
for (int i = 0; i < 10; i++) {
  // The closure references the iteration variable directly.
  // If the closures are evaluated after the loop, they all have the same value.
  closures1 << { -> println(i) }
}
for (closure in closures1) {
  closure()
}


def closures2 = [];
for (int i = 0; i < 10; i++) {
  // The closures reference the local variables.
  // If they are evaluated after the loop, they reference distinct values.
  int j = i;
  closures2 << { -> println(j) }
}
for (closure in closures2) {
  closure()
}