Search code examples
kotlingradlebuild.gradlegradle-kotlin-dsl

Gradle + Kotlin why don't we assign variables directly


In the build.gradle.kts there is the following code:

buildscript {
extra.apply {
    set("kotestVersion", "4.6.1")
    set("jdbi3Version", "3.21.0")
    set("resilience4jVersion", "1.7.1")
}
}
val kotestVersion: String by extra
val jdbi3Version: String by extra
val resilience4jVersion: String? by extra

Why do we need to assign values in such an indirect way? Is there a reason we do not assign a value to a variable directly, such as

val kotestVersion: String = "4.6.1"

Solution

  • Assuming you mean why do you need to use the set method, that’s because these are Gradle Lazy Properties, and not primitive types like string or int. The Groovy syntax makes it possible for direct assignments, but Kotlin doesn’t. There’s an open ticket about it: https://github.com/gradle/gradle/issues/9268