Search code examples
androidkotlingradle-kotlin-dsl

How do I declare extra properties in project level `build.gradle.kts` file?


How can I write this Groovy code to declare top level versions of the dependencies in the project level build.gradle.kts file written in Kotlin DSL code. How do I write it correctly?

buildscript {
   ext {
       compose_version = '1.5.3'
       lifecycle_version = '2.5.1'
       room_version = '2.5.2'
   }
}

Solution

  • This is how you can declare top-level configuration and variables in the build.gradle.kts file on top of the project using Kotlin DSL for Gradle.

    Here I use buildscript { extra.apply { set() } }. This way we can declare common dependency versions to all the modules in an app.

    // Top-level build file where you can add configuration options common to all sub-projects/modules.
    buildscript {
        extra.apply {
            set("compose_version", "1.5.3")
            set("lifecycle_version", "2.5.1")
            set("room_version", "2.5.2")
        }
    }
    

    Then, we can use the global variable in the module level build.gradle.kts indicating the version as ${rootProject.extra["library_version"]}

    dependencies {
        implementation("androidx.room:room-runtime:${rootProject.extra["room_version"]}")
    }