Search code examples
gradle-kotlin-dsl

Refactoring apply from buildscript when moving from groovy to kts


I have android project where I am trying to move from groovy to kts.

In the top-level build.gradle file I have this section

buildscript {
    apply { from(rootProject.file("gradle/versions.gradle.kts")) }
...
}

How do I refactor this apply when moving from groovy to kts?

The version.gradle.kts itself contains stuff like

val okhttpVersion = "4.9.3"
extra["okhttp"] = "com.squareup.okhttp3:okhttp:$okhttpVersion"

which then I want to reference as

dependencies {
    implementation(rootProject.ext.okhttp)
}

I have done "searches" on SO to see if there is hint on how to use apply from and initializing version & package name map and then use it. Perhaps I am not searching for right term. Would appreciate any pointers! 🙇🏽‍♂️


Solution

  • You may just refactor your apply block like this:

    buildscript {
        apply(from = rootProject.file("gradle/versions.gradle.kts"))
        // ...
    }
    

    And use implementation like this:

    dependencies {
        implementation(rootProject.extra["okhttp"] as String)
    }