How to configure every Kotlin project in Gradle multi-project build?

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.* )


The kotlin plugin being applied is actually not KotlinPlugin but KotlinPluginWrapper. Also it's necessary to use the canonical name to find the type.

plugins.withType(org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapper) {
    // All the stuff that all Kotlin sub-projects have in common
    ...
}

To catch all wrapper implementations, KotlinBasePluginWrapper could be used as well.


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