I spent quite a while with Google to find some information on this topic, but results relating to both Java enums and covariant return types were pretty much non-existent.
So: is it possible to use covariant return types with enum methods where you define a method in the enum class and then override it in the instances, like so:
package enumcovariance.test;
public enum CovariantEnum {
INT_INSTANCE(new Integer(3)) {
@Override
public Integer getData () {
return (Integer) super.getData();
}
},
STR_INSTANCE("Hello world") {
@Override
public String getData () {
return (String) super.getData();
}
};
private final Object data;
private CovariantEnum(Object data) {
this.data = data;
}
public Object getData () {
return data;
}
}
And then to take advantage of the covariance like so:
package enumcovariance.test;
import org.junit.Test;
public class CovariantEnumTest {
@Test
public void intEnumTest () {
Integer i = CovariantEnum.INT_INSTANCE.getData();
}
@Test
public void strEnumTest() {
String s = CovariantEnum.STR_INSTANCE.getData();
}
}
In this case the compiler is fine with my enum definition, but the test case fails to compile, saying Object cannot be converted to Integer (or String). Apparently the compiler only looks at the base definition of the method, not the overriding method. With a different enum definition I had the base method abstract, but that still didn't work.
I'm thinking it's something complex to do with the way enums are transformed during the compile process that prevents it from working, but I want to be sure it's not just me doing something silly.
Note that this test case is admittedly very contrieved, in my actual enum this functionality would be more useful. I can post it if necessary.
The type of CovariantEnum.INT_INSTANCE
is CovariantEnum
which returns Object
from getData
.
Unfortunately, you can't make the enum
type generic either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With