Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java covariant return types not working for overriding methods of an enum instance?

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.

like image 819
Søren Boisen Avatar asked Nov 05 '22 04:11

Søren Boisen


1 Answers

The type of CovariantEnum.INT_INSTANCE is CovariantEnum which returns Object from getData.

Unfortunately, you can't make the enum type generic either.

like image 114
Tom Hawtin - tackline Avatar answered Nov 09 '22 11:11

Tom Hawtin - tackline