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

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

    My general formula for simulating algebraic data types is:

    • The type is an abstract base class, and the constructors are subclasses of that
    • The data for each constructor are defined in each subclass. (This allows constructors with different numbers of data to work correctly. It also removes the need to maintain invariants like only one variable is non-null or stuff like that).
    • The constructors of the subclasses serve to construct the value for each constructor.
    • To deconstruct it, one uses instanceof to check the constructor, and downcast to the appropriate type to get the data.

    So for Either a b, it would be something like this:

    abstract class Either { }
    class Left extends Either {
        public A left_value;
        public Left(A a) { left_value = a; }
    }
    class Right extends Either {
        public B right_value;
        public Right(B b) { right_value = b; }
    }
    
    // to construct it
    Either foo = new Left(some_A_value);
    Either bar = new Right(some_B_value);
    
    // to deconstruct it
    if (foo instanceof Left) {
        Left foo_left = (Left)foo;
        // do stuff with foo_left.a
    } else if (foo instanceof Right) {
        Right foo_right = (Right)foo;
        // do stuff with foo_right.b
    }
    

提交回复
热议问题