Bad iteraction between the compact constructor and parameters captured by a lambda

forax at univ-mlv.fr forax at univ-mlv.fr
Sat Oct 24 22:29:16 UTC 2020


----- Mail original -----
> De: "Brian Goetz" <brian.goetz at oracle.com>
> À: "Remi Forax" <forax at univ-mlv.fr>, "amber-spec-experts" <amber-spec-experts at openjdk.java.net>
> Envoyé: Samedi 24 Octobre 2020 23:47:42
> Objet: Re: Bad iteraction between the compact constructor and parameters captured by a lambda

> On 10/24/2020 4:45 PM, Remi Forax wrote:
>> When we have decided to ban
>>    this.items = items
>> in the compact constructor and ask our users to use an assignment instead,
>> it has a stupid side effect to make the parameters inside the compact
>> constructor not effectively final, so a lambda can not capture them.
>>
>> So a code like this doesn't compile :(
>>    
>>    record Matrix(int[][] items) {
>>      Matrix {
>>        var copy = new int[items.length];
>>        Arrays.setAll(copy, i -> items[i].clone());
>>        items = copy;  // items is not effectively final anymore
>>      }
>>    }
> 
> But, is this any different than capturing any other constructor
> parameter that you mutate in the body?


Nope, but you don't have to re-assign the parameter is a plain old constructor,
you can use
  this.parameter = parameter;

In a compact constructor, if you do a defensive copy, you have too change the value of the parameter.

Rémi



More information about the amber-spec-experts mailing list