Philippe
Philippe

Reputation: 2007

How to define a variable for all Gradle subprojects using Gradle Kotlin DSL

I am following this guide.

The guide reads: Extra properties on a project are visible from its subprojects. This does not seem to work for me, as the following does not work:

In build.gradle.kts I have:

val ktorVersion by extra("1.3.2")

In subproject/build.gradle.kts I have:

dependencies {
    implementation("io.ktor:ktor-server-core:$ktorVersion")
}

Upvotes: 26

Views: 27012

Answers (3)

Alexander
Alexander

Reputation: 473

root build.gradle.kts

buildscript {
    val ktorVersion by extra("1.2.3")
    //OR
    //extra.set("ktorVersion", "1.2.3")
}

project build.gradle.kts

dependencies {
    val ktorVersion : String by rootProject.extra
    implementation("io.ktor:ktor-server-core:$ktorVersion")
    //OR
    //implementation("io.ktor:ktor-server-core:${rootProject.extra.get("ktorVersion")}
}

From here

Upvotes: 1

sedovav
sedovav

Reputation: 2046

Also, you may define the versions in an object inside the buildSrc project. buildSrc is a special project in Gradle, all declarations from it are visible across all Gradle projects (except settings.gradle.kts). So you may have

buildSrc/src/main/kotlin/myPackage/Versions.kt

object Versions {
  const val ktorVersion = "1.2.3"
}

And then use it from any your build.gradle (.kts) files

import myPackage.Versions.ktorVersion

dependencies {
  implementation("io.ktor:ktor-server-core:$ktorVersion")
}

UPD: currently recommended way to solve this problem is to use https://docs.gradle.org/current/userguide/platforms.html

dependencies {
    implementation(libs.groovy.core)
    implementation(libs.groovy.json)
    implementation(libs.groovy.nio)
}

Upvotes: 13

ckunder
ckunder

Reputation: 2300

In the project level build.gradle.kts:

val ktorVersion by extra { "1.3.2" }

In the subproject/build.gradle.kts:

val ktorVersion: String by rootProject.extra

dependencies {  
   implementation("io.ktor:ktor-server-core:$ktorVersion")
}

For more info: Gradle docs on Extra properties

Upvotes: 32

Related Questions