Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
}
like image 472
Philippe Avatar asked Jul 17 '20 17:07

Philippe


People also ask

What is the Kotlin Gradle DSL?

Gradle's Kotlin DSL provides an alternative syntax to the traditional Groovy DSL with an enhanced editing experience in supported IDEs, with superior content assist, refactoring, documentation, and more.

What is DSL in Gradle?

Simply, it stands for 'Domain Specific Language'. IMO, in gradle context, DSL gives you a gradle specific way to form your build scripts. More precisely, it's a plugin-based build system that defines a way of setting up your build script using (mainly) building blocks defined in various plugins.


2 Answers

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

like image 174
ckunder Avatar answered Oct 24 '22 07:10

ckunder


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")
}
like image 9
sedovav Avatar answered Oct 24 '22 08:10

sedovav