I am trying a very simple example with jdk-19 preview of pattern matching:
static String asString(Object value) {
return switch (value) {
case String s && s.length() > 10 -> "bigger then 10 : " + s;
case String s -> "less then 10 " + s;
case Collection<?> c -> "collection : " + c;
case null -> "null";
default -> value.toString();
};
}
To my surprise this fails to compile with jdk-19, but works fine with jdk-17. Is this an intentional change or a tiny bug?
The error is :
One.java:13: error: : or -> expected
case String s && s.length() > 10 -> "bigger then 10 : " + s;
^
One.java:13: error: illegal start of expression
case String s && s.length() > 10 -> "bigger then 10 : " + s;
^
One.java:13: error: ';' expected
case String s && s.length() > 10 -> "bigger then 10 : " + s;
^
One.java:13: error: not a statement
case String s && s.length() > 10 -> "bigger then 10 : " + s;
^
Note: One.java uses preview features of Java SE 19.
Note: Recompile with -Xlint:preview for details.
4 errors
Also java -version
:
openjdk version "19" 2022-09-20
OpenJDK Runtime Environment (build 19+37)
OpenJDK 64-Bit Server VM (build 19+37, mixed mode, sharing)
You probably should use the when
clause
static String asString(Object value) {
return switch (value) {
// Note the `when` here
case String s when s.length() > 10 -> "bigger then 10 : " + s;
case String s -> "less then 10 " + s;
case Collection<?> c -> "collection : " + c;
case null -> "null";
default -> value.toString();
};
}