[record] Marker annotation for overridden accessors

Tagir Valeev amaembo at gmail.com
Fri Jan 10 03:47:25 UTC 2020


Java has a good habit of explicitly marking specific code elements
with annotations when they convey a special meaning to avoid
accidental loss of this meaning. E.g.:

@Override: method overrides a superclass method: it's an error if it doesn't
@FunctionalInterface: an interface is a functional interface: it's an
error if it doesn't
@Serial: a method/field is a part of serialization infrastructure: not
sure whether it's completely implemented, but it would be a good idea
to issue error/warning if a wrong method is annotated.

Now we have new "special" methods: record accessors. They cannot be
annotated with @Override but they technically override the
auto-generated implementation. Probably we should introduce a new
annotation that designates the intention to override the accessor?

record Foo(List<String> list) {
  public List<String> list() {
    return Collections.unmodifiableList(this.list);

So if we rename the method without renaming the record component, we
will have a compilation error now. What do you think?

I also thought about an annotation to designate the canonical
constructor and concluded that it's useless because it's impossible to
mistakenly make a constructor non-canonical. E.g.:

record Interval(int from, int to) {
  public Interval(int from, int to) {
    if(from < to) { this.from = from; this.to = to; }
    else { this.to = from; this.from = to; }

We may want to add a new component, e.g. `boolean closed` and forget
to update the canonical constructor. However, this immediately creates
a compilation error, because new implicit canonical constructor will
be generated, and now existing explicit constructor must delegate.
Essentially, in a working program, the absence of delegation in the
constructor body already marks the constructor as canonical.

With best regards,
Tagir Valeev.

More information about the amber-spec-experts mailing list