How can I simulate Haskell's “Either a b” in Java

后端 未结 14 2353
梦毁少年i
梦毁少年i 2020-12-07 22:40

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)         


        
14条回答
  •  Happy的楠姐
    2020-12-07 23:16

    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.

提交回复
热议问题