0

I like to apply the explicit API mode to all modules in this Android project except to the app module. This works fine by adding the following configuration to the build.gradle file of each module.

// build.gradle of a module

kotlin {    
    explicitApi() 
}

I like to however avoid the repetitive declaration. Therefore, I aim to configure it once it the build.gradle file in the project root. I tried the following:

// build.gradle in project root

allprojects {
    apply plugin: "kotlin"
    kotlin {
        if (project.name != "app") {
            explicitApi()
        }
    }
}

This collides with the plugin definition in the modules:

Caused by: org.gradle.api.internal.plugins.PluginApplicationException: Failed to apply plugin 'kotlin-android'.
Caused by: java.lang.IllegalArgumentException: Cannot add extension with name 'kotlin', as there is an extension already registered with that name.
Caused by: com.android.build.gradle.internal.BadPluginException: The 'java' plugin has been applied, but it is not compatible with the Android plugins.

Related

JJD
  • 50,076
  • 60
  • 203
  • 339

1 Answers1

4

Your build.gradle applies the Kotlin plugin to subprojects before they apply the Android plugin, which doesn't work - it needs to be the other way around.

Try postponing the action until after the project is evaluated, for example

gradle.afterProject { project ->
    if (project.name == "app") return
    project.extensions.findByName("kotlin")?.explicitApi()
}
ephemient
  • 198,619
  • 38
  • 280
  • 391
  • Thank you. If I understand correctly, this does the same as `Gradle#projectsEvaluated(Closure)` with the advantage that `Gradle#afterProject(Closure)` provides access to the `project` parameter. – JJD Oct 21 '20 at 16:55
  • 1
    @JJD `projectsEvaluated` invokes its closure once after all projects are evaluated. `afterProject` invokes its closure immediately after each project is evaluated. `projectsEvaluated { allprojects { ... } }` would be *similar* to `afterProject {... }` but it is not quite the same thing. – ephemient Oct 21 '20 at 18:46