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

Lothar Schulz
lotharschulz
Published in
2 min readSep 8, 2022

--

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.

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

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)
}

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

Originally published at https://www.lotharschulz.info.

--

--