Transient fields in records

Brian Goetz brian.goetz at oracle.com
Thu Dec 22 14:25:45 UTC 2022


The problem you are confronting is not that the record can’t have transient fields; it can’t have fields *at all* that are not part of the state description.   A record is the state, the whole state, and nothing but the state.

On Dec 22, 2022, at 7:37 AM, John Hendrikx <hjohn at xs4all.nl<mailto:hjohn at xs4all.nl>> wrote:

Hi,

I have tried googling this topic and looking through the amber-dev and amber-spec-experts archives, but was unable to locate anything that mentioned transient fields in combination with records. The JEP itself also makes no mention of transient fields.  The word transient seems to never be mentioned in combination with records anywhere...

I often enough design classes for serialization in some fashion or other.  One of the tools that one can use here is to use transient fields to store information that can be completely derived from the other fields.  These are used to store information that may be too large to store or too expensive to (re)calculate on every access.  All major frameworks that do serialization recognize such fields and act accordingly (Java serialization, Jackson, Hibernate).

However, records do not allow such fields, even though I think one of their primary use cases is data storage, which often will sooner or later involve serialization.  Now I can't imagine this was an oversight, so I'm curious to know if transient fields were simply left out for now, or that they are not allowed for other reasons.

Javac simply complains: TransientRecord.java:4: error: field declaration must be static

Here is the use case I had when I encountered this problem:

    public record Message( A a, B b, C c, D d) {
      public enum Type {
          A, B, C, D;
      }

      private final transient List<Type> types;   // <<< not allowed

      public Message {
          List<Type> types = new ArrayList<>();

          if(a != null) {
              types.add(Type.A);
          }
          if(b != null) {
              types.add(Type.B);
          }
          if(c != null) {
              types.add(Type.C);
          }
          if(d != null) {
              types.add(Type.D);
          }

          this.types = Collections.unmodifiableList(types);
      }

      public List<Type> getTypes() {
          return types;   // use transient field to avoid recalculation
      }
    }

--John

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


More information about the amber-dev mailing list