Search code examples
gradlekotlinbuild.gradlereusabilitycode-reuse

How to define reusable blocks in gradle build


I'm writing a gradle build for a kotlin project where I want to reuse the same kotlinOptions in multiple tasks.

At the moment my build script looks like this, as the kotlinOptions are the same for every task I don't want to write them over and over again.

compileKotlin {
    kotlinOptions {
        allWarningsAsErrors = true
        freeCompilerArgs = ["-Xjvm-default=enable", "-Xjsr305=strict"]
        jvmTarget = "1.8"
    }
}

compileTestKotlin {
    kotlinOptions {
        allWarningsAsErrors = true
        freeCompilerArgs = ["-Xjvm-default=enable", "-Xjsr305=strict"]
        jvmTarget = "1.8"
    }
}

compileIntegrationTestKotlin {
    kotlinOptions {
        allWarningsAsErrors = true
        freeCompilerArgs = ["-Xjvm-default=enable", "-Xjsr305=strict"]
        jvmTarget = "1.8"
    }
}

Instead I want to define them once and reuse the definition whereever I need it.

I also tried the following (As suggested in Alexs answer)

ext.optionNameHere = {
    allWarningsAsErrors = true
    freeCompilerArgs = ["-Xjvm-default=enable", "-Xjsr305=strict"]
    jvmTarget = "1.8"
}
compileKotlin { kotlinOptions = ext.optionNameHere }
compileTestKotlin { kotlinOptions = ext.optionNameHere }
compileIntegrationTestKotlin { kotlinOptions = ext.optionNameHere }

which leads to following error message:

> Cannot get property 'kotlinOptions' on extra properties extension as it does not exist


Solution

  • I found a solution for my specific problem (just for the kotlin compile part). I would love to have a more general approach. Though this might help others.

    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
        kotlinOptions {
            // ...
        }
    }
    

    From the kotlin docs.