My colleague Rod presented me with the following (paraphrased):
public interface Executable<T> {
T execute();
}
The question arose: What if an implementor doesn't have a meaningful value to return?
public class MyExecutable implements Executable<____> {
// ...
}
You could fill in the blank with Object and return null or this, perhaps. However, we agreed that this doesn't communicate as well to its clients the fact that there really isn't a return value and it shouldn't even be used. You can't use primitive void since it really isn't a type, and is a primitive anyhow (forbidden as a generic type parameter). What to do?
How about java.lang.Void?
public class MyExecutable implements Executable<Void> {
public Void execute() {
// do stuff
return null;
}
}
We felt that this clearly communicated that there's no useful return value for the functor. In fact, since java.lang.Void is uninstantiable, the only value the functor could return is null. Nifty, eh? Ever think you'd use java.lang.Void?
Jaggregate internally uses a number of generic functors that really don't need to return anything. I changed them to return java.lang.Void instead of Object, and I'm happy with the results.
Look at section #2 in the 0.5 specification on closure conversion.
If I understand the language correctly, you can use type java.lang.Void in place of the void keyword. I think this exegesis covers your case:
"The closure conversion supports converting a function that yields no result to an interface whose method returns java.lang.Void. In this case a null value is returned from the function. This is necessary to write APIs that support completion transparency: that is, in which an invocation of the API can return normally if and only if the function that is passed to it can complete normally."
Or not. There is no example in the specification for this case that I found.
Posted by: B. K. Oxley (binkley) | May 07, 2008 at 18:08
I would suggest you simply create two categories of functors, those that return Void, and those that return all other Objects. C-based languages treat Void functions specially, it creates some problems, but I usually like to stay within the grain of whichever languages I'm working with.
Check out: http://www.codeproject.com/KB/java/FunctionalJava.aspx
a package of generic functors and an immutable Iterable type featuring method chaining, lazy evaulation, and typical functional projections like map, filter, and fold.
Posted by: Stephen Swensen | December 21, 2009 at 09:30