Enum vs Record vs Sealed types

Remi Forax forax at univ-mlv.fr
Thu Jan 2 20:52:34 UTC 2020

Now that the design of Record is mostly stabilized, i think we should talk about the relation between an enum, a record and a sealed type.

As we have done with records, we can work backward from the pattern matching switch to see what we need for an enum.

So let suppose that like Java2D, we fill a shape with a Paint, Paint being an interface between a solid color and a gradient. 
sealed Paint permits Color, LinearGradient { }
enum Color implements Paint{
  RED(255, 0, 0), BLACK(0, 0, 0), WHITE(255, 255, 255);
  private final int red, green, blue;
record LinearGradient(Point start, Color startColor, Point end, Color endColor) implements Paint {
  int getRed(int x, int y) { ... }
  int getGreen(int x, int y) { ... }
  int getBlue(int x, int y) { ... }

In that case, we may want to be able to switch on a special value (like RED), on an enum and on a Gradient which is a record.

int redAt(Paint paint, int x, int y) {
  return switch(paint) {
    case RED -> 255;
    case Color(var red, _, _) -> red;
    case LinearGradient gradient -> gradient.getRed(x, y);

So should we allow record components on an enum with the following rule:
- either an enum use the record like syntax
  enum Color(int red, int green, int blue) { ... }
  and in that case, no supplementary fields are allowed.
- or an enum doesn't use the record like syntax and in that case, it's the classical enum.

The other solution, is to wait to have de-constructor, in that case we may not need a special syntax for enum.


More information about the amber-spec-experts mailing list