public void testRecursiveFunctionImplementedAsProvider() throws Exception {
FunInjector injector = FunGuice.createInjector(new FunModule() {
protected void configure() {
bindFunction(Integer.class, Integer.class)
.toProvider(FactorialProvider.class);
}
});
Function<Integer, Integer> factorial =
injector.getFunction(Integer.class, Integer.class);
assertEquals(1, (int) factorial.make(1));
assertEquals(2, (int) factorial.make(2));
assertEquals(6, (int) factorial.make(3));
assertEquals(24, (int) factorial.make(4));
}
private static class FactorialProvider implements Provider<Integer> {
@Inject
private int parameter;
@Inject
private Function<Integer,Integer> factorial;
public Integer get() {
if (parameter == 1) {
return 1;
} else if (parameter > 1) {
return factorial.make(parameter - 1) * parameter;
} else {
throw new RuntimeException("not implemented for " + parameter);
}
}
}
You can download the source here:
http://slesinsky.org/brian/downloads/fun-guice.zip
You might also find RequestScopeTest interesting; it shows various
ways to implement request scopes using functions.
- Brian