Manage Gradle dependencies using Kotlin code in buildSrc
Updated:
Deprecated
Gradle now includes Version Catalogs, allowing dependency coordinates and versions to be shared between subprojects. On top of this, Gradle generates a type-safe API to reference these dependencies in your build scripts. It is recommended to use Version Catalogs instead of what is discussed in this article. This article will no longer be maintained, meaning the code samples may become out-of-date. Please check out my latest articles for more up-to-date topics.
Find out moreUsing Kotlin to maintain our Gradle dependencies within the buildSrc directory can be really great.
- Allows us to use a familiar syntax
- Provides auto-complete within Groovy or Kotlin Gradle scripts
- Can click through to a particular dependencies definition
Sweet!
→ /buildSrc/src/main/java/com/myapp/Versions.kt
package com.myapp
object Versions {
object AndroidX {
const val appCompat = "1.0.2"
}
const val kotlin = "1.3.10"
...
}
→ /buildSrc/src/main/java/com/myapp/Libs.kt
package com.myapp
object Libs {
object AndroidX {
const val appCompat = "androidx.appcompat:appcompat:${Versions.AndroidX.appCompat}"
}
const val kotlinStdlib = "org.jetbrains.kotlin:kotlin-stdlib:${Versions.kotlin}"
}
→ /src/app/build.gradle
import com.myapp.Libs
dependencies {
implementation Libs.kotlinStdlib
implementation Libs.AndroidX.appCompat
}
I hope the article was useful. If you have any feedback or questions please feel free to reach out.
Thanks for reading!
WRITTEN BY
Andrew Lord
A software developer and tech leader from the UK. Writing articles that focus on all aspects of Android and iOS development using Kotlin and Swift.
Want to read more?
Here are some other articles you may enjoy.