Why don't enums allow generics since Java 5? (was "Re: 2 questions about enums and the closed/withdrawn JEP 301")

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Thu Mar 30 01:18:10 UTC 2023


Hi David,
sadly I don’t know the answer to your question as I wasn’t around when 
enums were added to the language ;-)

I agree with all Brian said. I’d also add that the failure modes we 
discovered when we worked on generic enums are rather obscure, as they 
are a result of /three/ factors: (i) you need to have some class Foo 
that is transitioning from being non-generic to being generic and (ii) 
you have to have some existing utterances of Foo nested inside some 
other parameterized type (e.g. |Box<Foo>|) and (iii) the declaration of 
that second generic class has to be sufficiently strict (e.g. |Box<X 
extends Foo<X>>|). If /all/ these conditions are met, then you end up 
with cases where utterances of |Box<Foo>|were valid before 
generification of Foo, but invalid afterwards. Something like this was 
(and still is!) pretty hard to spot.

One might argue (given what we know now) that it would have been perhaps 
better not to make the Enum class itself generic. But the static type 
checking you get on stuff like |EnumSet.noneOf(Foo.class)| is hard to 
pass up: if |Enum| wasn’t a generic class, then there’d be no way to tie 
the type of the class literal to the type of the returned EnumSet. So I 
think the Enum generic declaration we ended up with is the result of a 
forced move (type-system wise).

Maurizio

On 29/03/2023 19:43, David Alayachew wrote:

> Hello Maurizio,
>
> I hope you don't mind me asking, but no one else has answered my 2nd 
> question. And since you were the one who wrote up most of these links 
> that I am referencing, it's a decent shot to see if you know the 
> answer lol.
>
> Why were enums never given generics in the first place? I know they 
> came out in the same release, so theoretically, that was the best time 
> possible to bake this feature in and ensure it played well from the 
> beginning. Why didn't they?
>
> Thank you for your help and patience!
> David Alayachew

​
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20230330/1280e0e1/attachment-0001.htm>


More information about the amber-dev mailing list