21

When I tried to build my Java code which has switch expressions using Gradle, it throws this error:

error: switch expressions are a preview feature and are disabled by default.

I tried running ./gradlew build --enable-preview which didn't work either.

I'm using Gradle 5.3.1.

Matthias Braun
  • 24,493
  • 16
  • 114
  • 144
Murali Krishna
  • 499
  • 1
  • 7
  • 15

3 Answers3

25

You need to configure the JavaCompile tasks, so that Gradle passes this option to the Java compiler when compiling.

Something like this should work:

tasks.withType(JavaCompile).each {
    it.options.compilerArgs.add('--enable-preview')
}

To run the app/tests we need to add jvmArgs.

Example:

test {
    jvmArgs(['--enable-preview'])
}
Matthias Braun
  • 24,493
  • 16
  • 114
  • 144
JB Nizet
  • 633,450
  • 80
  • 1,108
  • 1,174
  • 1
    also if I have to run the app or run the tests, I've to add this `test { jvmArgs(['--enable-preview']) } run { jvmArgs(['--enable-preview']) }` – Murali Krishna Mar 30 '19 at 18:25
  • 2
    Since I include the [application plugin](https://docs.gradle.org/current/userguide/application_plugin.html), I use `applicationDefaultJvmArgs += ["--enable-preview"]` instead of `test {jvmArgs(['--enable-preview'])}`. – Matthias Braun Jun 23 '19 at 09:38
19

Currently there seem not to be a single place for defining that. You should do it for all of the task types (compile, test runtime or java exec related tasks). I found myself fully covered with:

tasks.withType(JavaCompile) {
    options.compilerArgs += "--enable-preview"
}

tasks.withType(Test) {
    jvmArgs += "--enable-preview"
}

tasks.withType(JavaExec) {
    jvmArgs += '--enable-preview'
}
Aleksander Lech
  • 786
  • 7
  • 15
9

Here is another version using the Gradle Kotlin DSL for usage in build.gradle.kts:

plugins {
    `java-library`
}

repositories {
    mavenCentral()
}

java {
    sourceCompatibility = JavaVersion.VERSION_12
}

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

dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter-api:5.4.2")
    testImplementation("org.junit.jupiter:junit-jupiter-engine:5.4.2")
}

bentolor
  • 2,636
  • 2
  • 18
  • 30