Introduced by a guard? (Question on Draft Spec for JEP 440 and 441)
David Alayachew
davidalayachew at gmail.com
Sun Apr 9 00:27:36 UTC 2023
Hello Amber Dev Team,
Thank you Gavin for posting the spec!
> 6.3.4 Scope for Pattern Variables in Switch Labels
>
> Pattern variables can be introduced by case labels with a
> case pattern, either by the pattern itself or by a guard,
> and are in scope for the relevant parts of the associated
> switch expression (6.3.1.6) or switch statement (6.3.2.6)
>
> The following rules apply to case labels:
>
> * A pattern variable is introduced by a case label
> with a case pattern p if it is declared by p.
>
> * A pattern variable declared by the pattern of a
> guarded case pattern is definitely matched in the
> associated guard.
>
> - It is a compile-time error if any pattern
> variable declared by the pattern of a guarded
> case pattern is already in scope at its guard.
>
> * A pattern variable is introduced by a guarded case
> label if it is introduced by the associated guard
> when true (6.3.1).
Reading the bullets here (especially the final bullet point) implies to me
that the only time that the guard of a guarded case pattern can introduce
variables is when the guard contains a pattern match itself. So, something
like this.
Number input = 4;
String response =
switch (input) {
case Number n when n instanceof Integer i -> String.valueOf(i);
default -> "idc";
};
Apologies for the terrible example.
However, when reading the sentences in the quoted text above the bullets,
they seem a lot more loose. More specifically, reading that text makes me
think something like this is possible (obviously illegal and nonsensical
code, but trying to make a point).
switch (someObject)
{
case Integer i when (int abc = method()) == i -> "???";
default -> "idk";
};
Apologies for the terrible example.
I guess my question is, is there another way besides patterns for a
variable to be introduced in the guard?
And if not, would it make more sense to instead say something like the
following instead?
> Pattern variables can be introduced by case labels with a
> case pattern, either by the pattern itself or by a guard
> containing a pattern, and are in scope for the relevant
> parts of the associated switch expression (6.3.1.6) or
> switch statement (6.3.2.6)
Apologies if this is just noise, but I wanted to bring it up because I
initially parsed the quoted passage to imply the second code example I
gave. It wasn't until several minutes of reading and screwing around in
jshell did I start to think the passage was actually implying the first
code example I gave.
Thank you for your time and help!
David Alayachew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20230408/8b06d2e7/attachment.htm>
More information about the amber-dev
mailing list