Questions about the record pattern

Hunor Szegi hunor.szegi at gmail.com
Mon Jun 20 14:40:32 UTC 2022


Hi All,

I'm looking at the record pattern (JEP 405):

"A record pattern consists of a type, a (possibly empty) record component
pattern list which is used to match against the corresponding record
components, and an optional identifier."

(I guess the pattern should be matching to the original list of record
components, and it isn't related to the constructors. (Or is it possible
that the non-canonical constructors could be used here?) I presume not, as
then a pattern check could have side effects as well.)

So let's see an example record:

record Box(Object content, int size) {}

The following pattern case label won't work: "case Box(i, j) ->" , as "i"
and "j" are not patterns. I see the point to describe the structure as
simply as possible. And given that a single variable can't be a pattern,
it's difficult to cover both the "Box(i, j)" and a compound "Box(String i,
int j)" pattern. But from the user perspective it would be the most
straightforward.

If the type of the components are given (no "overloaded" constructor could
play a role), why is it necessary to provide the type in the pattern? Of
course the possibility of providing a subtype of the component is
beneficial, but that can be treated as a compound pattern - a record
pattern, which optionally can contain type patterns.

I saw this example: "Point(var x, var y) - so this is a special case of the
type pattern, where the component type is inferred. But why is the "var"
necessary here? Isn't it a counterexample, which breaks the specification,
as "var x" isn't a pattern. Indeed it is very similar to a type pattern,
but not exactly that. (You can't write "case var i ->".)

I can imagine a modified specification, instead of a list of patterns,
using a list of "pattern variable or pattern".

Maybe I misunderstood something, as of course I wasn't able to try it. In
this case sorry in advance.

Finally some questions:

case Box(Box(String x, int y) a, int z) b ->

I haven't seen a similar example in the JEP, but based on the description,
both the "a" and "b" pattern variables should be allowed, isn't it? (It
would be good.)

And can we use a constant as pattern, or the null pattern? For example:

case Box(Box(null, int y) a, 3) b ->

Thank you in advance,

Regards,
Hunor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20220620/d925f100/attachment-0001.htm>


More information about the amber-dev mailing list