为什么不能在build.gradle.kts中使用`const val`

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

遵循限制,我尝试定义一个版本常量:

const val kotlinVersion = "1.3.72"

plugins {
    java
    kotlin("jvm") version kotlinVersion
}

但是这失败并显示消息

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?

评论
不懂珍惜
不懂珍惜

即使您的构建脚本似乎是顶级的,也并非如此。 gradle文档在解释构建的生命周期时提到了这一点:

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 (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.

点赞
评论