javaandroidgradle

Compiler exception when using Java 21 pattern matching in Android


I saw Java 21 introduced pattern matching in Switch statements. This was ideal for some code I had, and I wanted to use it instead of a bunch of if-if-else.

Here's a test class I made:

public class Test {
    static <T> void checkType(T value) {
        switch (value) {
            case Integer i -> System.out.println("Integer");
            case String s -> System.out.println("String");
            default -> throw new IllegalArgumentException("Unsupported type: " + value.getClass());
        }
    }

    public static void main(String[] args) {
        checkType("Some string");
        checkType(21);
    }
}

java Test.java has the following output:

String
Integer

When I try to do the same thing in Android, I get the following compile error:

An exception has occurred in the compiler (21.0.3). Please file a bug against the Java compiler via the Java bug reporting page (https://bugreport.java.com) after checking the Bug Database (https://bugs.java.com) for duplicates. Include your program, the following diagnostic, and the parameters passed to the Java compiler in your report. Thank you.
com.sun.tools.javac.code.Symbol$CompletionFailure: class file for java.lang.runtime.SwitchBootstraps not found

Both are using Java 21.0.3, and I have tried with 22.0.1. I have tried both with the Oracle JDK as well as OpenJDK from Microsoft.

I have set the appropriate parameters in my build.gradle.ktsas well (compileOptions& kotlinOptions).


Solution

  • I am an absolute buffoon, I've literally dealt with this before, I just didn't think it was this. Android itself doesn't support Java 21, currently the max is 17: read here, and even then, it might not support all Java 17 APIs.

    Regardless, the min sdk I set would have made it even lower.