javapattern-matchingjava-19

jdk-19 pattern switch fails to compile


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)

Solution

  • 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();
            };
        }
    

    Reference: https://docs.oracle.com/en/java/javase/19/language/pattern-matching.html#GUID-A5C220F6-F70A-4FE2-ADB8-3B8883A67E8A