Combining records and enumerations

Simon Ritter sritter at azul.com
Tue Oct 12 20:10:14 UTC 2021


I hope this is the right list to post this to.

I was recently using an enumeration and it struck me that enums 
containing a constructor and member declarations could be simplified by 
adopting some of the syntax from records.

Here is an example of such an enumeration:

public enum Planet {
   MERCURY(0.4, 0.055),
   VENUS(0.7, 0.815),
   EARTH(1.0, 1.0),
   MARS(0.107, 1.5);

   private double orbitalDistance;
   private double earthMass;

   Planet(double orbitalDistance, double earthMass) {
     this.orbitalDistance = orbitalDistance;
     this.earthMass = earthMass;
   }

   public double orbitalDistance() {
     return orbitalDistance;
   }

   public double earthMass() {
     return earthMass;
   }
}

Most of this boiler-plate code is identical to the code eliminated by a 
record from a simple data class.  If we took the same approach we could 
simplify this as:

public enum Planet(double orbitalDistance, double earthMass) {
   MERCURY(0.4, 0.055),
   VENUS(0.7, 0.815),
   EARTH(1.0, 1.0),
   MARS(0.107, 1.5);
}

The grammar for enumerations would only need to be extended to include 
an EnumHeader

EnumDeclaration: {ClassModifier} enum TypeIdentifier EnumHeader 
[ClassImplements] EnumBody

with EnumHeader using the same format as RecordHeader

EnumHeader:
   ( [EnumComponentList] )

I'm assuming changes to the compiler to implement this would not be 
overly complex (although I have not looked at the code).

I'd be very interested to hear other people's opinion on this.

Regards,

Simon.



More information about the amber-dev mailing list