javac rejects canonical constructor when formal parameter name doesn't match the record component name
Tagir Valeev
amaembo at gmail.com
Wed Dec 25 08:28:36 UTC 2019
Well, one place where people might dislike it is the established code
style. Some projects may always use prefixed field names as
constructor parameters to avoid 'this.' qualifier in assignments.
Being unable to follow the same style in the records might be
irritating.
On the other hand, this simplifies things for IDE developers. I'm
thinking about "make canonical constructor compact" quick-fix
(available if canonical constructor ends with explicit assignment of
some record components and has no returns, no custom parameter
annotations, etc.) I thought it should be quite a difficult problem in
general as we would need to rename parameters, solve possible name
conflicts, possibly qualify fields with 'this.', etc. Having the
restriction that names must be equal, the quick-fix implementation
will be much simpler.
With best regards,
Tagir Valeev.
On Wed, Dec 25, 2019 at 12:53 AM Brian Goetz <brian.goetz at oracle.com> wrote:
>
> On this one, I agree with the compiler and think the spec should be adjusted.
>
> The reasoning is that I am looking down he road at named parameter invocation, and if the record component names mismatch the canonical ctor param names, that will cause trouble for no benefit.
>
> Sent from my iPad
>
> > On Dec 24, 2019, at 5:50 AM, Tagir Valeev <amaembo at gmail.com> wrote:
> >
> > Hello!
> >
> > javac 14-ea+28-1366 rejects the following code:
> >
> > record R(int x) {
> > public R(int _x) { this.x = _x; }
> > }
> >
> > Test.java:2: error: invalid canonical constructor in record R
> > public R(int _x) { this.x = _x; }
> > ^
> > (invalid parameter names in canonical constructor)
> > Note: Test.java uses preview language features.
> > Note: Recompile with -Xlint:preview for details.
> >
> > However, the spec for the records [1] doesn't prohibit such a
> > renaming. It says only that "The types of the formal parameters in the
> > formal parameter list of the canonical constructor must be identical
> > to the declared type of the corresponding record component." The
> > formal parameter names are only mentioned in "derived constructor
> > signature" definition. However, this definition doesn't prohibit
> > anything, to my understanding. So either compiler should be updated to
> > allow such a code or spec should be updated to explicitly prohibit it.
> >
> > With best regards,
> > Tagir Valeev.
> >
> > [1] http://cr.openjdk.java.net/~gbierman/jep359/jep359-20191125/specs/records-jls.html#jls-8.10.4
>
More information about the amber-dev
mailing list