23

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")
}
Philippe
  • 1,715
  • 4
  • 25
  • 49

2 Answers2

25

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

ckunder
  • 1,920
  • 1
  • 10
  • 10
13

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)
}
sedovav
  • 1,986
  • 1
  • 17
  • 28
  • This is cleaner. The other option is fugly. – jimmy_terra Nov 06 '20 at 01:36
  • This is cleaner since we don't have to redeclare `ktorVersion` on sub-projects. – HendraWD Jun 22 '21 at 03:23
  • 7
    Cleaner but might be slower because update of ANY version in buildSrc/src/main/kotlin/myPackage/Versions.kt will cause gradle to recompile build scripts. See https://melix.github.io/blog/2021/03/version-catalogs.html – sergeidyga Sep 19 '21 at 09:53