I'd like to define a version constant in guild.gradle.kts
file so that it can be used even in the plugins
block. The plugins
block requires restricted syntax:
«plugin version»
must be constant, literal, strings
Following the restriction I tried to define the a version constant:
const val kotlinVersion = "1.3.72"
plugins {
java
kotlin("jvm") version kotlinVersion
}
However this fails with message
Const 'val' are only allowed on top level or in objects
even though the declaration seem to meet all const requirements. Why cannot be const val
used in build.gradle.kts?
Even though it seems like your build script is top level, it isn't. The gradle docs mentions this when explaining the lifecycle of the build:
Finally, evaluate each
Project
by executing itsbuild.gradle
file, if present, against the project.
(source) This means that in your kotlin build scripts, the receiver type (i.e. this
) is KotlinBuildScript
which is eventually a subclass of Project
. I don't know the details about how it's evaluated, but I can imagine it would be equivalent to what you can do in Kotlin with receiver types:
fun Project.evaluate(buildScript: Project.() -> Unit) = this.evaluate()
So your build script is really just the inside of a closure, hence why you can't use const val
.