java EnumSet, incompatible types: inference variable E has incompatible bounds

2.7k Views Asked by At

I have a the below method which returns a enum set containing all of the elements of Types:

@Override
public EnumSet<?> groupTypes() {
    return EnumSet.allOf(Types.class);
}

And the Types is an enum like below:

public enum Types implements GroupType {
    ASG;
}

The GroupType interface is:

 public interface GroupType extends NamedType {

 }

The NamedType interface:

public interface NamedType {

    String name();

}

When compile, I got the below error:

    error: incompatible types: inference variable E has incompatible bounds
return EnumSet.allOf(Types.class);
                        ^

equality constraints: Types
    upper bounds: Enum<CAP#1>,Enum<E>
  where E is a type-variable:
    E extends Enum<E> declared in method <E>allOf(Class<E>)
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Enum<CAP#1> from capture of ?
1

There are 1 best solutions below

0
On

The error

Error: incompatible types: inference variable E has incompatible bounds return EnumSet.allOf(Types.class);

is telling you what is the problem. One way to resolve is to change the signature like this

public EnumSet<? extends NamedType> groupTypes() {
        return EnumSet.allOf(Types.class);
    }

or you can just assign EnumSet.allOf(Types.class) to a variable and then there is no need to change the method signature like this

public EnumSet<?> groupTypes() {
    EnumSet<Types> typeses = EnumSet.allOf(Types.class);
    return typeses;
}