How to set Java Pattern Matching for switch in IntelliJ & Gradle

Pattern Matching for switch is a preview feature in Java 17. This post explains how to enable Pattern Matching for switch in IntelliJ IDE and Gradle build tool.

~ 2 minutes read

Code

    public static List<GHRepository> listRepositories(GHOrganization gitHubOrganization){
        GitHubRepository gitHubRepository = listGitHubRepositories(gitHubOrganization);
        switch (gitHubRepository) {
            case GitHubRepositorySuccess gitHubRepositorySuccess -> {
                return gitHubRepositorySuccess.ghRepositories();
            }
            case GitHubRepositoryFailure gitHubRepositoryFailure -> {
                return Collections.emptyList();
            }
        }
        return Collections.emptyList();
    }

source

GitHubRepository is a java sealed interface and permits two java records that implement this interface:

In order to make the code work above, you need to enable preview view in IntelliJ & Gradle.

IntelliJ IDE

Go to File -> Project Structure -> Project.

Choose 17 (Preview) language level to make IntelliJ accept the code above.

Gradle

val ENABLE_PREVIEW = "--enable-preview"
tasks.withType<JavaCompile> {
    options.compilerArgs.add(ENABLE_PREVIEW)
}
tasks.test {
    useJUnitPlatform()
    jvmArgs(ENABLE_PREVIEW)
}

source

Add the snippet above to your build.gradle.kts build descriptor file.

Use the –enable-preview java flag to run the jar:

./gradlew clean build && java --enable-preview -jar app/build/dist/app.jar -o Sealed-Classes-Kotlin-Java

Code Repository

Find the Code Repository with all the code in

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.