Search code examples
gradleandroid-gradle-plugindocumentationdeprecatedgradle-kotlin-dsl

How to replace the deprecated plugin function with the apply function in Gradle


The Android Studio's Empty Activity default configuration calls the plugin function in two places:

in the FirstEmpty/build.gradle.kts script:

import org.gradle.kotlin.dsl.support.compileKotlinScriptModuleTo

// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    alias(libs.plugins.androidApplication) apply false
    alias(libs.plugins.jetbrainsKotlinAndroid) apply false
}

and in the FirstEmpty/app/build.gradle.kts script:

plugins {
    alias(libs.plugins.androidApplication)
    alias(libs.plugins.jetbrainsKotlinAndroid)
}

plugins is defined in KotlinBuildScript, which will be deprecated:

Deprecated

Will be removed in Gradle 9.0

plugin is supposed to be replaced by apply:

If you need to apply a plugin imperatively, please use apply() or apply(plugin = "id") instead.

project(":core") {
    apply(plugin = "java")
}

The above quote and the following statement make me believe that the plugins call can be replaced with an apply call with no repercussions on the rest of the script:

The plugins {} block serves a similar purpose to the apply method that can be used to apply a plugin directly to a Project object or similar. A key difference is that plugins applied via the plugins {} block are conceptually applied to the script, and by extension the script target. At this time there is no observable practical difference between the two approaches with regard to the end result.

Please show me how to do it in this particular case.


Solution

  • No changes are needed to your build: that is a best practice project layout.

    plugins in those instances is not defined in KotlinBuildScript anymore but in KotlinProjectScriptTemplate.

    The plugins block from there is very much in use and is recommended in preference to using the apply method. The apply method does not add the plugin to your build classpath and does not give the script access to Kotlin DSL accessors.