How to refer to gradle configuration set in gradle.properties with Kotlin DSL?

1.5k Views Asked by At

I'm trying to adopt the Kotlin Gradle DSL. I have a gradle.properties with, among other things:

slf4jVersion=2.0.0-alpha1

I declare the dependency in build.gradle.kts with:

implementation( name = "slf4j-api",
  group = "org.slf4j", version = project.properties["slf4jVersion"].toString())

Yes, it works, but it also smells. The issue is the ugliness of project.properties["slf4jVersion"].toString()

Shouldn't I be able to just write slf4jVersion? It makes standard configuration look like a custom hack. What is the canonical and succinct way to keep version numbers together in a separate file with the Kotlin Gradle DSL?

1

There are 1 best solutions below

3
Saurabh Thorat On

You can access project properties via delegated properties.

In your build.gradle.kts:

val slf4jVersion: String by project
implementation(name = "slf4j-api", group = "org.slf4j", version = slf4jVersion)

Official sample: https://github.com/gradle/kotlin-dsl-samples/blob/3c977388f78bdcff1f7ed466e8d27feb5bf32275/samples/project-properties/build.gradle.kts#L14