Make Primary Constructor an independant feature

Remi Forax forax at univ-mlv.fr
Fri Apr 12 19:38:13 UTC 2019


I think there is a merit to separate the primary constructor feature from other features of a record.

This afternoon while fixing a bug, i took a look to the classes around to see if it was possible to transform them to records. But i've found that in more than half of the cases, the classes were not representing data but just carrier so having the getters, hashCode and equals automatically generated was the factor that hamper me to transform the classes into records.   

Given that a record is a data carrier, i'm wondering if it makes sense to say that a record = data + carrier i.e. to separate the data part (getters + equals + hashCode) from the carrier part (the initialization using a primary constructor). The idea is that a primary constructor can be applied not only to records, but also to classes, enums and later value classes.

Here are some examples,
  For a result of a function, having an equals/hashCode can be harmful (maybe the error code is not stable)
    class Result(int value, int errorCode);

  For most of the structural patterns, having getters is not helpful
    class UserProxy(User user) implements User {
      UserProxy {
        requireNonNull(user);
      }
      ...
    }

  An enum that stores an integer, all constants have to initialize the value
    enum Flag(int flag) {
      READ(8), WRITE(16)
      ;

      public boolean isAllowedBy(int flags) {
        return flags & flag != 0;
      }
    }

Rémi




More information about the amber-spec-experts mailing list