29

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
  • 32,039
  • 22
  • 142
  • 171
Murali Krishna
  • 619
  • 2
  • 9
  • 16

3 Answers3

35

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
  • 32,039
  • 22
  • 142
  • 171
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 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
27

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
  • 1,105
  • 12
  • 16
11

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
  • 3,126
  • 2
  • 22
  • 33