Enhanced Enums Redux (with working code)
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Mon Feb 23 12:26:38 UTC 2026
Hi Clement
On 22/02/2026 18:21, Clement Cherlin wrote:
> Greetings,
>
> I have been working on the problem of generic enums off and on for
> quite some time (see
> https://github.com/Mooninaut/cursed-generic-enum-java for a previous
> dead-end attempt).
>
> I think I have an actual solution this time, and it doesn't require
> any changes to Java's type system. It only requires a slight tweak to
> the "extends" clause of generic enums: Replace "extends
> Enum<SomeEnum<T>>" with "extends Enum SomeEnum<?>>".
I'd need more time to think about the consequences of this. That said,
this has a good property, in that it only affects generic enum
declarations. Non-generic enum would stay exactly the same.
>
> There is one slightly awkward issue. It's not possible to simply pass
> an enum class literal to EnumSet's static factory methods without a
> raw cast.
>
> EnumSet.allOf((Class<Option<?>>) (Class) Option.class);
This makes me more worried -- because this is such a common idiom that
(I think) has to work like for any other enum.
In the spirit of your earlier suggestion, a possible way out would be to
also redefine what Foo.class mean when Foo is a generic enum -- e.g. not
just Class<Foo> (class-of-raw) but Class<Foo<?>> (class-of-wildcard).
All such changes would indeed help making generic enums more useful
(and interoperable with EnumSet and friends), but whether all such
changes are actually "sound", that's a different story.
For instance, code like:
MyEnumSet<Option> set = MyEnumSet.allOf(Option.class)
Would _still_ fail. You need the LHS to be _exactly_
MyEnumSet<Option<?>> for this to work. Which means graduating an enum
into a generic enum would still be a source incompatible change.
Cheers
Maurizio
More information about the amber-dev
mailing list