Guarded pattern with total primary pattern inside instanceof
Tagir Valeev
amaembo at gmail.com
Mon Oct 25 06:01:20 UTC 2021
Hello!
I tried the following code:
public class Demo {
static void test(Object obj) {
if (obj instanceof (Object o && String.valueOf(o).equals("null"))) {
System.out.println("null");
}
}
public static void main(String[] args) {
test(null);
test("null");
}
}
As (Object o && String.valueOf(o).equals("null")) is not a total
pattern, I expect this code to be compilable successfully (and it
should print "null" once). However, javac has its own opinion:
Demo.java:5: error: expression type Object is a subtype of pattern type Object
if (obj instanceof (Object o && String.valueOf(o).equals("null"))) {
^
I'm using
openjdk version "17" 2021-09-14
OpenJDK Runtime Environment (build 17+35-2724)
Spec is quite unambiguous here [1], so I believe it's a javac problem.
[1] https://docs.oracle.com/javase/specs/jls/se17/preview/specs/patterns-switch-jls.html#jls-15.20.2
More information about the amber-dev
mailing list