How can I write a typesafe Java method that returns either something of class a or something of class b? For example:
public ... either(boolean b) {
if (b)
Here is a statically checked type-safe solution; this means you cannot create runtime errors. Please read the previous sentence in the way it is meant. Yes, you can provoke exceptions in some way or the other...
It's pretty verbose, but hey, it's Java!
public class Either {
interface Function {
public void apply(T x);
}
private A left = null;
private B right = null;
private Either(A a,B b) {
left = a;
right = b;
}
public static Either left(A a) {
return new Either(a,null);
}
public static Either right(B b) {
return new Either(null,b);
}
/* Here's the important part: */
public void fold(Function ifLeft, Function ifRight) {
if(right == null)
ifLeft.apply(left);
else
ifRight.apply(right);
}
public static void main(String[] args) {
Either e1 = Either.left("foo");
e1.fold(
new Function() {
public void apply(String x) {
System.out.println(x);
}
},
new Function() {
public void apply(Integer x) {
System.out.println("Integer: " + x);
}
});
}
}
You might want to look at Functional Java and Tony Morris' blog.
Here is the link to the implementation of Either
in Functional Java. The fold
in my example is called either
there. They have a more sophisticated version of fold
, that is able to return a value (which seems appropriate for functional programming style).