Possible Pattern Matching for switch (Third Preview) bug
Remi Forax
forax at univ-mlv.fr
Mon Aug 1 12:12:26 UTC 2022
> From: "Jordan Zimmerman" <jordan at jordanzimmerman.com>
> To: "amber-dev" <amber-dev at openjdk.org>
> Sent: Monday, August 1, 2022 1:58:24 PM
> Subject: Possible Pattern Matching for switch (Third Preview) bug
> There doesn't seem to be a way to have a switch case pattern for multiple
> related patterns. Given that it works in an instanceof pattern I would think it
> might work in a switch pattern. But, maybe not. Anyway here's what I found.
> Given:
>> public interface MyFace {}
>> public record MyEye() implements MyFace {}
>> public record MyNose() implements MyFace {}
>> public void examine(Object face) {
>> switch (face) {
>> case MyEye eye, MyNose nose -> System.out.println("part of my face");
>> default -> System.out.println("Not part of my face");
>> }
>> }
> This produces: "illegal fall-through to a pattern".
> However, this works with an instanceof pattern. E.g.
>> public void examine(Object face) {
>> if ((face instanceof MyEye eye) || (face instanceof MyNose nose)) {
>> System.out.println("part of my face");
>> }
>> else {
>> System.out.println("Not part of my face");
>> }
>> }
> Of course, the instanceof test is not very useful as the bound variables "eye"
> or "nose" are only scoped to the immediate test (and not in the if block). So,
> this may not be a bug? Anyway, I thought I'd mention it. For the switch it
> would be useful to have common behavior for several related patterns without
> having to use a method to do it. The bound variables would be ignored (maybe
> via an upcoming wonderbar "_").
yes, that's one possible future, introduce '_' so one can write
public void examine(Object o) {
switch (o) {
case MyEye _, MyNose _ -> System.out.println("part of my face");
default -> System.out.println("Not part of my face");
}
}
But we have to answer to the question: where we can put '_' ? as method parameter, lambda parameter, catch parameter, local variable, etc
Perhaps we do not need '_', and it's "better" to allow the type pattern to be declared without a binding like the record pattern has an optional binding for the whole pattern ?
> Cheers.
> -Jordan
regards,
Rémi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20220801/21da75d7/attachment.htm>
More information about the amber-dev
mailing list