The problem I'm having has already been asked before: How to implement an interface with an enum, where the interface extends Comparable?
However, none of the solutions solve my exact problem, which is this:
I have a value object, similar to BigDecimal
. Sometimes this value will not be set with a real object, because that value is not yet known. So I want to use the Null Object Pattern to represent the times this object is not defined. This is all not a problem, until I try to make my Null Object implement the Comparable
interface. Here's an SSCCE to illustrate:
public class ComparableEnumHarness {
public static interface Foo extends Comparable<Foo> {
int getValue();
}
public static class VerySimpleFoo implements Foo {
private final int value;
public VerySimpleFoo(int value) {
this.value = value;
}
@Override
public int compareTo(Foo f) {
return Integer.valueOf(value).compareTo(f.getValue());
}
@Override
public int getValue() {
return value;
}
}
// Error is in the following line:
// The interface Comparable cannot be implemented more than once with different arguments:
// Comparable<ComparableEnumHarness.NullFoo> and Comparable<ComparableEnumHarness.Foo>
public static enum NullFoo implements Foo {
INSTANCE;
@Override
public int compareTo(Foo f) {
return f == this ? 0 : -1; // NullFoo is less than everything except itself
}
@Override
public int getValue() {
return Integer.MIN_VALUE;
}
}
}
Other concerns:
- In the real example, there are multiple subclasses of what I'm calling
Foo
here. - I could probably work around this by having
NullFoo
not be anenum
, but then I can't guarantee there is ever only exactly one instance of it, i.e. Effective Java Item 3, pg. 17-18