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

后端 未结 14 2410
梦毁少年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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 23:32

    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);
        }   
    }
    

提交回复
热议问题