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)
Thanks to Derive4J algebraic data types are now very easy in Java. All you have to do is create the following class:
import java.util.function.Function;
@Data
public abstract class Either {
Either(){}
/**
* The catamorphism for either. Folds over this either breaking into left or right.
*
* @param left The function to call if this is left.
* @param right The function to call if this is right.
* @return The reduced value.
*/
public abstract X either(Function left, Function right);
}
And Derive4J will take care of creating constructors for the left and rights cases, as well as a pattern matching syntax alla Haskell, mapper methods for each sides, and more.