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)
My general formula for simulating algebraic data types is:
instanceof to check the constructor, and downcast to the appropriate type to get the data.So for Either a b, it would be something like this:
abstract class Either { }
class Left extends Either {
public A left_value;
public Left(A a) { left_value = a; }
}
class Right extends Either {
public B right_value;
public Right(B b) { right_value = b; }
}
// to construct it
Either foo = new Left(some_A_value);
Either bar = new Right(some_B_value);
// to deconstruct it
if (foo instanceof Left) {
Left foo_left = (Left)foo;
// do stuff with foo_left.a
} else if (foo instanceof Right) {
Right foo_right = (Right)foo;
// do stuff with foo_right.b
}