Skip to content

Instantly share code, notes, and snippets.

@guillaumebort
Created March 19, 2011 11:56
Show Gist options
  • Save guillaumebort/877428 to your computer and use it in GitHub Desktop.
Save guillaumebort/877428 to your computer and use it in GitHub Desktop.
For play.libs.F ?
package scrapbook;
import java.lang.reflect.InvocationTargetException;
public class Test {
public static void main(String[] args) {
// Standard function
Function<String,String> toUpperCase = new Function<String,String>() {{ b = a.toUpperCase(); }};
assertTrue( toUpperCase.invoke("kiki").equals("KIKI") );
// Closure
final Integer maxLength = 6;
Function<String,Boolean> isLengthOk = new Function<String, Boolean>() {{ b = a.length() <= maxLength; }};
assertTrue( isLengthOk.invoke("coco") == true );
assertTrue( isLengthOk.invoke("guillaume") == false );
}
// ----- With:
public static void assertTrue(Boolean v) {
if(!v) throw new RuntimeException("Assertion failed");
}
public static class Val<T> {
T t;
public Val(T t) {
this.t = t;
}
}
public static abstract class Function<A, B> {
A a;
B b;
private Function() {
try {
if (input.get() != null) {
a = ((Val<A>) input.get()).t;
} else {
_closedValues = new Object[this.getClass().getDeclaredFields().length];
for (int i = 0; i < _closedValues.length; i++) {
_closedValues[i] = this.getClass().getDeclaredFields()[i].get(this);
}
a = (A)"";
}
} catch (Exception e) {
throw new RuntimeException("Function declaration", e);
}
}
private Object[] _closedValues;
static final ThreadLocal<Val> input = new ThreadLocal<Val>();
public B invoke(A a) {
input.set(new Val<A>(a));
try {
Function<A, B> invoked = (Function<A, B>) this.getClass().getDeclaredConstructors()[0].newInstance(_closedValues);
return invoked.b;
} catch (InvocationTargetException e) {
throw new RuntimeException("Function invocation exception", e.getTargetException());
} catch (Exception e) {
throw new RuntimeException("Function instantiation exception", e);
} finally {
input.remove();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment