androidkotlingradlegroovykotlin-gradle-plugin

How to apply explicit API mode to all modules except the app module?


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


Solution

  • 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()
    }