Closures Basic Usage - UnquietCode/Closures-for-Java GitHub Wiki
These examples and more are located in the repository under '/src/test/java/unquietcode/stately/closure/'.
public void inputTypes() {
final String string = "hello"; // a final variable is accessible inside
int X = 10; // not accessible, but can still be passed in
final int dummyX = X; // this will provide alternative access inside
Closure1<Integer, Integer> adder = new AbstractClosure1<Integer, Integer>(X) { // <-passing in a variable
int x = this.<Integer>a1(); // will have to use this somtimes for some compilers
int y = (Integer) a1(); // this will work all of the time
Integer z = a1(); // how it should always work, ideally
int base = 12; // of course, this always works
public Integer run(Integer p1) {
// access the final variables
out(string + " " + dummyX);
// can also get that X from the passed in variable
out(string + " " + a1());
// could look up by argument number instead of convenience method
out(string + " " + arg(1));
// or use our declared variables
out(string + " " + x);
out(string + " " + y);
out(string + " " + z);
// and we also get our parameter value
out(string + " " + p1);
// then we return an Integer
return base + p1 + (Integer) a1() + x + y + z;
}
};
// Now we can run it!
out(adder.run(5));
}