In Haskell, we can define types with multiple, mutually exclusive value constructors, such as the Maybe type, which is defined as follows:
data Maybe a = Nothing | Just a
where 'a' is any existing type. It'd be nice if we could do something similar in Java. For instance, if we wanted to define an extended real number in Haskell, we could do something like
data ExtendedReal = Infinity | Real Double
In Java, the only way I can think of creating a class with similar functionality is by putting a boolean flag in the class that overrides the double. For instance, we could do
public class ExtendedReal {
private double real;
private boolean isInfinity;
public ExtendedReal() {
isInfinity = true;
}
public ExtendedReal(double real) {
this.real = real;
}
...
...
}
and then check for the flag in all of your methods.
Is there a more canonical way of achieving this?
Double.isInfinite.