Search code examples
javaenumsenumset

Converting from EnumSet<A> to Set<B> when A inherits from B


The title pretty much explains the question. I have an interface method:

Set<Field> getFieldSet()

and I have a class, User which looks something like this

class User {
    enum Fields implements Field {
        USERNAME, PASSWORD;
        ...
    }
    ...
}

Now I want to implement User's getFieldSet() method. The naive way seems to just return EnumSet.allOf(Fields.class) but I get the following error:

> Type mismatch: cannot convert from Set<User.Fields> to Set<Field>

Other than manually copying the EnumSet to Set<Field>, is there a good way to do this?


Solution

  • You could return new HashSet<Field>(EnumSet.allOf(Fields.class));.

    That will get around the fact that you can't assign a value of type Set<User.Fields> to a variable of type Set<Field>.

    Alternatively, your interface could be Set<? extends Field> getFields() instead. You can assign Set<User.Field> to a capturing variable.