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

后端 未结 14 2420
梦毁少年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:12

    The big thing is not to try to write in one language whilst writing in another. Generally in Java you want to put the behaviour in the object, rather than having a "script" running outside with encapsulation destroyed by get methods. There is no context for making that kind of suggestion here.

    One safe way of dealing with this particular little fragment is to write it as a callback. Similar to a very simple visitor.

    public interface Either {
        void string(String value);
        void integer(int value);
    }
    
    public void either(Either handler, boolean b) throws IntException {
        if (b) {
            handler.string("test");
        } else {
            handler.integer(new Integer(1));
        }
    }
    

    You may well want to implement with pure functions and return a value to the calling context.

    public interface Either {
        R string(String value);
        R integer(int value);
    }
    
    public  R either(Either handler, boolean b) throws IntException {
        return b ?
            handler.string("test") :
            handler.integer(new Integer(1));
    }
    

    (Use Void (capital 'V') if you want to get back to being uninterested in the return value.)

提交回复
热议问题