有什么方法可以在Java中定义求和类型?Java似乎自然地直接支持产品类型,我认为枚举可能允许它支持求和类型,而继承看起来也许可以做到,但是至少有一种情况我无法解决。详细地说,求和类型是可以恰好具有一组不同类型之一的类型,例如C中的标记联合。就我而言,我正在尝试在Java中实现haskell的Either类型:
data Either a b = Left a | Right b
但在基本级别上,我必须将其实现为产品类型,而忽略其字段之一:
public class Either
{
private L left = null;
private R right = null;
public static Either right(R right)
{
return new Either<>(null, right);
}
public static Either left(L left)
{
return new Either<>(left, null);
}
private Either(L left, R right) throws IllegalArgumentException
{
this.left = left;
this.right = right;
if (left != null && right != null)
{
throw new IllegalArgumentException("An Either cannot be created with two values");
}
if (left == right)
{
throw new IllegalArgumentException("An Either cannot be created without a value");
}
}
.
.
.
}
我尝试通过继承来实现,但是我必须使用通配符类型参数或等效参数,Java泛型不允许使用:
public class Left extends Either
我没有太多使用Java的Enums,但是尽管它们似乎是次佳的候选者,但我并不抱有希望。
在这一点上,我认为只有通过类型转换Object值才有可能做到这一点,我希望完全避免这种情况,除非有一种方法可以安全,一次性地对所有求和类型使用它。