如何编写返回类a或类b的类型安全的Java方法?例如:

public ... either(boolean b) {
  if (b) {
    return new Integer(1);
  } else {
    return new String("hi");
  }
}

什么是最干净的方法?

(我想到的唯一的事情就是使用显然很糟糕的异常,因为它滥用了通用语言功能的错误处理机制...
public String either(boolean b) throws IntException {
  if (b) {
    return new String("test");
  } else {
    throw new IntException(new Integer(1));
  }
}

)

最佳答案

我模拟代数数据类型的一般公式是:

  • 该类型是一个抽象基类,而构造函数是该
  • 的子类。
  • 每个子类中都定义了每个构造函数的数据。 (这允许具有不同数量数据的构造函数正常工作。它也不需要维护不变式,例如仅一个变量为非null或类似的东西)。
  • 子类的构造函数用于构造每个构造函数的值。
  • 要对其进行解构,可以使用instanceof来检查构造函数,然后向下转换为适当的类型以获取数据。

  • 因此,对于Either a b,它将是这样的:
    abstract class Either<A, B> { }
    class Left<A, B> extends Either<A, B> {
        public A left_value;
        public Left(A a) { left_value = a; }
    }
    class Right<A, B> extends Either<A, B> {
        public B right_value;
        public Right(B b) { right_value = b; }
    }
    
    // to construct it
    Either<A, B> foo = new Left<A, B>(some_A_value);
    Either<A, B> bar = new Right<A, B>(some_B_value);
    
    // to deconstruct it
    if (foo instanceof Left) {
        Left<A, B> foo_left = (Left<A, B>)foo;
        // do stuff with foo_left.a
    } else if (foo instanceof Right) {
        Right<A, B> foo_right = (Right<A, B>)foo;
        // do stuff with foo_right.b
    }
    

    09-10 12:37
    查看更多