简体   繁体   中英

Why cannot be `const val` used in build.gradle.kts

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 its build.gradle file, if present, against the project.

(source ) This means that in your kotlin build scripts, the receiver type (ie 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM