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)
The closest I can think of is a wrapper around both values that lets you check which value is set and retrieve it:
class Either {
boolean isLeft;
TLeft left;
TRight right;
Either(boolean isLeft, TLeft left1, TRight right) {
isLeft = isLeft;
left = left;
this.right = right;
}
public boolean isLeft() {
return isLeft;
}
public TLeft getLeft() {
if (isLeft()) {
return left;
} else {
throw new RuntimeException();
}
}
public TRight getRight() {
if (!isLeft()) {
return right;
} else {
throw new RuntimeException();
}
}
public static Either newLeft(L left, Class rightType) {
return new Either(true, left, null);
}
public static Either newRight(Class leftType, R right) {
return new Either(false, null, right);
}
}
class Main {
public static void main(String[] args) {
Either foo;
foo = getString();
foo = getInteger();
}
private static Either getInteger() {
return Either.newRight(String.class, 123);
}
private static Either getString() {
return Either.newLeft("abc", Integer.class);
}
}