Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typed subsets of enums

Tags:

java

Let's say I have the following enum type:

public enum Country {
    CHINA,
    JAPAN,
    FRANCE,
    // ... and all other countries
    AUSTRIA,
    POLAND;
}

Now I would to create a subset of this enum, conceptually like:

public enum EuropeanUnion constraints Country {
    FRANCE,
    // ... and all other countries within the European Union
    AUSTRIA,
    POLAND;
}

public enum LandlockedCountries constraints Country {
    // ... all landlocked countries
    AUSTRIA;
}

I'd like to create subsets of an enum type so that I can write methods such as

Set<Person> getNationalMembersOfEuropeanParliament(EuropeanUnion euCountry);

Using the subtype EuropeanUnion for parameter euCountry protects the API user from accidentally passing in an invalid country, e.g. the non-EU JAPAN.

Are there any ways of "constraining" the range of valid enum values so that one can benefit from the static type system?

like image 218
Abdull Avatar asked Jul 02 '15 19:07

Abdull


1 Answers

You might want to consider using an EnumSet; this won't give you new types, but it lets you work with collections of enum values in a set-theoretic way:

public enum Country {
    CHINA,
    JAPAN,
    ...;

    public static final EnumSet<Country> EUROPEAN_UNION = EnumSet.of(Country.FRANCE, Country.AUSTRIA, ...);
}

EnumSet implements Set, so you can use e.g. addAll(), removeAll() and retainAll() to produce unions, differences, and intersections (just remember to copy the left-hand-side set first).

like image 180
Aasmund Eldhuset Avatar answered Oct 05 '22 01:10

Aasmund Eldhuset