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

后端 未结 14 2409
梦毁少年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条回答
  •  醉酒成梦
    2020-12-07 23:11

    Based on the answer by Riccardo, following code snippet worked for me:

    public class Either {
            private L left_value;
            private R right_value;
            private boolean right;
    
            public L getLeft() {
                if(!right) {
                    return left_value;
                } else {
                    throw new IllegalArgumentException("Left is not initialized");
                }
            }
    
            public R getRight() {
                if(right) {
                    return right_value;
                } else {
                    throw new IllegalArgumentException("Right is not initialized");
                }
            }
    
            public boolean isRight() {
                return right;
            }
    
            public Either(L left_v, Void right_v) {
               this.left_value = left_v;
               this.right = false;
            }
    
            public Either(Void left_v, R right_v) {
              this.right_value = right_v;
              right = true;
            }
    
        }
    

    Usage:

    Either onlyString = new Either("string", null);
    Either onlyInt = new Either(null, new Integer(1));
    
    if(!onlyString.isRight()) {
      String s = onlyString.getLeft();
    }
    

提交回复
热议问题