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?
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).
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