Skip to content

Instantly share code, notes, and snippets.

@ShinNoNoir
Created June 9, 2014 12:11
Show Gist options
  • Select an option

  • Save ShinNoNoir/82a9c6e49264301ec213 to your computer and use it in GitHub Desktop.

Select an option

Save ShinNoNoir/82a9c6e49264301ec213 to your computer and use it in GitHub Desktop.
Simple example demonstrating how Java can close over (final) variables
import java.util.ArrayList;
import java.util.List;
public class ClosureExample {
public static void main(String[] args) {
List<Runnable> actions = new ArrayList<>();
for (int i = 0; i < 10; i++) {
final int j = i;
actions.add(new Runnable() {
public void run() {
System.out.println("Captured: " + j);
}
});
}
for (Runnable action : actions) {
action.run();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment