JEP-468: Derived record creation in record methods with parameter

Brian Goetz brian.goetz at oracle.com
Tue Apr 30 12:43:10 UTC 2024


The meaning of names inside the block is the same as outside, with the 
addition of the synthetic component locals introduced by the `with` 
construct (which may shadow outer variables.)  So here `this` refers to 
the method on which `withReal` was invoked.

Of course, your example fails because `this.re` is a final field and 
assigning to it is not allowed.

On 4/30/2024 2:13 AM, Eirik Bjørsnøs wrote:
> Hi,
>
> JEP-468 briefly mentions that derived record expressions can also be 
> used inside the record class:
>
>     Derived record creation expressions can also be used inside record
>     classes to simplify the implementation of basic operations: 
>
>     record Complex(double re, double im) {
>         Complex conjugate() { return this with { im = -im; }; }
>         Complex realOnly()  { return this with { im = 0; }; }
>         Complex imOnly()    { return this with { re = 0; }; }
>     }
>
>
> I'm trying to understand what happens when a derived expression is 
> used in a record method taking a parameter with the same name as one 
> of the record components:
>
> record Complex(double re, double im) {
>     Complex withReal(double re) { return this with { re = ?; }; }
> }
>
> Can "this" be used inside the transformation block, like the following?
>
>       Complex withReal(double re) { return this with { this.re
>     <http://this.re> = re; }; }
>
>
> I know this particular example is a bit silly, but I think it may be 
> useful to combine multiple transformations in a single record method, 
> also when the method takes one or more parameters. People will be 
> running into this.
>
> Perhaps this could be clarified in the JEP with an example or does it 
> need clarification in the JLS? Or is it just me missing something, as 
> usual? :-)
>
> Thanks,
> Eirik.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20240430/9542faef/attachment.htm>


More information about the amber-dev mailing list