kotlingradlekotlin-dsl

How to reuse dependency versions in subprojects for Kotlin DSL?


I have a multi module Gradle project with Kotlin DSL as build file. Inside of the root build.gradle.kts there is dependencies section for root and subprojects with its own dependencies. I would like to create a variable that can keep version of some dependency and be used in all modules in build.gradle.kts.

Root build.gradle.kts looks like:

buildscript {
// ...
}
plugins {
// ...
}
subprojects {
// repositories, plugins, tasks, etc.

dependencies {
   implementation("com.fasterxml.jackson.core:jackson-databind:2.10.4")
}

Submodule common-module/build.gradle.kts

dependencies {
    implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.10.4")
}

I would like to declare a variable and assign the version for these dependencies as a value and only reuse it on modules. Some thing like implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-csv:${jacksonVersion}").

How can I do that?


Solution

  • The most modern, type-safe solution of this problem is using version catalogs.

    1. Update Gradle to at least 7.5.1.
    2. gradle/libs.versions.toml:
    [versions]
    jackson = "2.12.5"
    
    [libraries]
    jackson-databind = { module = "com.fasterxml.jackson:jackson-databind", version.ref = "jackson" }
    jackson-dataformat-csv = { module = "com.fasterxml.jackson.dataformat:jackson-dataformat-csv", version.ref = "jackson" }
    
    1. Add dependencies like implementation(libs.jackson.dataformat.csv) in all the subprojects.