Possible Pattern Matching for switch (Third Preview) bug

Jordan Zimmerman jordan at jordanzimmerman.com
Mon Aug 1 11:58:24 UTC 2022


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 "_").

Cheers.

-Jordan

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20220801/e654e928/attachment.htm>


More information about the amber-dev mailing list