I have a project that uses a Gradle multi-project build. Some of the sub-projects are written in Java, other newer ones in Kotlin.
We have one top-level build.gradle
file. This file contains following part:
allprojects {
plugins.withType(JavaPlugin) {
// All the stuff that all Java sub-projects have in common
...
}
// All the stuff that all sub-projects have in common
...
}
We now would like to introduce common settings for our Kotlin sub-projects, but I could not find out which withType
to use.
The build.gradle
files of our Kotlin projects start with
plugins {
id "org.jetbrains.kotlin.jvm" version "1.3.0"
}
but neither withType(org.jetbrains.kotlin.jvm)
nor withType(KotlinProject)
works.
What type do I have to use there? Thanks!
Creating a multi-project buildA multi-project build in Gradle consists of one root project, and one or more subprojects. This is the recommended project structure for starting any Gradle project.
The subproject producer defines a task named buildInfo that generates a properties file containing build information e.g. the project version. You can then map the task provider to its output file and Gradle will automatically establish a task dependency.
gradle files in an Android Studio project? Save this question.
You can reference the Kotlin plugin by its id
instead of its type, as follows:
allprojects {
plugins.withType(JavaPlugin) {
// All the stuff that all Java sub-projects have in common
// ...
}
plugins.withId("org.jetbrains.kotlin.jvm") {
// All the stuff that all Kotlin sub-projects have in common
// ...
}
}
For Java plugin it's easer and you can use plugins.withType
, as it's a "core" Gradle plugin, and the JavaPlugin
class can be used as it's part of the Gradle Default Imports ( import org.gradle.api.plugins.*
)
One solution is to start to use a custom plugin for your project. This is exactly what the AndroidX team did
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.jetbrains.kotlin.gradle.plugin.KotlinBasePluginWrapper
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
class MyPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.plugins.all {
when (it) {
...
is KotlinBasePluginWrapper -> {
project.tasks.withType(KotlinCompile::class.java).configureEach { compile ->
compile.kotlinOptions.allWarningsAsErrors = true
compile.kotlinOptions.jvmTarget = "1.8"
}
}
}
}
}
You'll need to setup all the boiler plate to get this setup, but the long term payoff is high.
Read more
https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/buildSrc/src/main/kotlin/androidx/build/AndroidXPlugin.kt#186
https://www.youtube.com/watch?v=sQC9-Rj2yLI&feature=youtu.be&t=429
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With