Questions about the record pattern
Brian Goetz
brian.goetz at oracle.com
Mon Jun 20 14:52:17 UTC 2022
> (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.)
Currently, records have a single deconstruction pattern -- the one
matching the record descriptor / canonical constructor. But in the
future, records, like other classes, could have more than one
deconstruction pattern, in which case we'd do overload selection prior
to matching.
Just as with method invocation, first we do overload selection, then we
do what we have to do to convert the arguments to the types of the
parameters. Similarly, with patterns, we do overload selection (trivial
right now with records), and then match the subpatterns to the bindings.
> 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.
Our principle here is: variables should be declared. Having i and j
spring into existence by virtual of being named in a pattern, *which
looks an awful lot like a method invocation*, is too subtle.
> If the type of the components are given (no "overloaded" constructor
> could play a role)
As said, this is a short-term state of affairs.
> 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
> ->".)
Because x should have a declaration.
I realize Python does it differently, but then again, it's dynamically
typed, so it's not really a fair comparison.
> 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.)
Correct, the inner `Box(String x, int y) a` is what we call a _named
record pattern_. This is not unlike the @ patterns in Haskell or Scala.
> And can we use a constant as pattern, or the null pattern? For example:
No, not yet. Constants (and null) are not currently patterns.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20220620/c2958ec6/attachment-0001.htm>
More information about the amber-dev
mailing list