Java records used in enums

Robert Marcano robert at marcanoonline.com
Fri May 21 14:54:18 UTC 2021


On 5/21/21 10:28 AM, Kasper Nielsen wrote:
> On Fri, 21 May 2021 at 14:51, Alberto Otero Rodríguez <albest512 at hotmail.com>
> wrote:
> 
>> Hi,
>>
>> I think enums in Java should be immutable. When you let the programmer
>> change values in an enum instance, an unexpected behaviour can happen when
>> using multiple threads as enum instances are static (singleton).
>>
>> So, I was wondering why not make enums instances be defined as records
>> instead of normal classes.
>>
> 
> Lots of reasons, for example:
> * It would be a breaking change for an almost non-existent problem.
> * All internal state of enums would now be public.
> * Enum's extend java.lang.Enum, records extend java.lang.Record.
>    java.lang.Enum cannot extend java.lang.Record because it has instance
> fields.
> 
> /Kasper
> 

I could add that making enum records would not solve the proposed 
"problem" because records are shallowly immutable.

I am sure that theoretically, simple enum implementations could be 
treated by the JIT internally as simple indexes as an optimization, I 
don't know if it does something like that already. So I don't think 
records will bring any improvement to enums


More information about the core-libs-dev mailing list