Java 14 records canonical constructor

Christian Beikov christian.beikov at gmail.com
Fri Jun 5 07:18:13 UTC 2020


Am 04.06.2020 um 22:37 schrieb Brian Goetz:
> To ask `x instanceof Rational(2, 4)` (assuming numeric literals are 
> the denotation of constant patterns), this expression is equivalent to 
> matching the pattern:
>
>     Rational(var _a, var _b)  && _a instanceof 2 && _b instanceof 4
>
> I think there's your answer.  The sub-patterns are not "passed" like 
> parameters to the deconstruction pattern; they stay at the use site, 
> and are applied monadically if the outer pattern matches.  There is no 
> Rational that will match the pattern `Rational(2, 4)`.
>> I guess what I am asking is, will the pattern cause a Rational object 
>> to be instantiated such that the normalization can happen for that 
>> pattern object as well? If not, then it seems to me that a canonical 
>> constructor that alters/mutates the arguments is broken and can't be 
>> used for pattern matching.
> I think maybe you just have a mental model of how records and/or 
> pattern matching works, and it isn't quite how it does work. (That's 
> fine, and we're happy to educate, but loaded words like "broken" are 
> probably best avoided.)
> Pattern matching is _destructuring_; taking a whole and destructuring 
> it into parts.  The output of a pattern match on a rational is going 
> to be some flavor of "numerator and denominator".
The destructuring makes sense. That's what I would have expected actually.
> I think what you're probably thinking is that asking `x instanceof 
> Rational(2, 4)` means "could x have come from the constructor 
> invocation `new Rational(2, 4)`.  But that's not what it means. 
> (Though you can ask this question easily by: r.equals(new 
> Rational(2,4))`.

I wasn't sure how this property of records, that they are "plain data 
carrieres" i.e. re-constructible through their component values, would 
be utilized and guess I thought it has to be utilized for something in 
the language e.g. pattern matching.

I still think it would be nice if it could be avoided that developers 
shoot their foot by implementing a non-idempotent canonical record 
constructor.



More information about the amber-dev mailing list