I mostly agree.  For the "record", here's one more possible reason I left out:

 - So you can put Javadoc on the fields.

Again, I don't find this one particularly compelling, but I wanted to put it in the record.

On 1/6/2020 11:10 AM, Tagir Valeev wrote:
Hello!

пн, 6 янв. 2020 г., 22:42 Brian Goetz <brian.go...@oracle.com <mailto:brian.go...@oracle.com>>:

      - Maybe the author wants annnotations on the fields that, were
    they to
    be put on the components, would be spread to places where they are
    _not_
    wanted.

    The last of these is the only one that is mildly compelling here,
    but, I
    wonder whether this is purely theoretical, or whether someone
    actually
    needs this.


I'm for not allowing this. I cannot imagine that custom annotation could be necessary. I saw many kinds of annotations but I don't think there's some scenario when it's necessary to annotate a private field of record and it cannot be covered by the corresponding annotation of record component or explicit accessor. Many annotations simply don't applicable to record fields. E.g. dependency injection like @Inject or @Autowired: this should be done via canonical constructor instead of reflection. Or Lombok's @Getter (who needs Lombok getters in record?), @Setter (field is final, no setter is possible). JPA injections are also should be done via the constructor, so record component annotation should be better. Static analyzer suppression annotations are also unlikely necessary: what could be suppressed for implicitly defined fields?

Well, it could be desired for nullability, e.g.:

record ListWrapper<T>(@Nullable List<T> list) {
  public ListWrapper {
    this.list = list == null ? List.of() : list;
  }

  public @NotNull List<T> list() { return list; } // IDE might warn here that you are returning nullable field from a method marked as not-null.
}

In this particular case, it could be desired to specify an explicit @NotNull on the field. However, this could be solved defaulting to @NotNull instead:

record ListWrapper<T>(@NotNull List<T> list) {
  public ListWrapper(@Nullable List<T> list) { // need to specify args here, but no need to override accessor method
    this.list = list == null ? List.of() : list;
  }
}

Even though we cannot use a compact constructor anymore, this looks clean solution to me.

In any case, we can allow it later if somebody comes up with an example where it's really necessary.

With best regards,
Tagir Valeev.


Reply via email to