因此,我一直在使用gradle的kotlin dsl,而我的buildscript已经发展到我想要引入自定义任务以更好地组织的程度。
这是我的build.gradle.kts
中的MWE:
open class CustomTask : DefaultTask() {
var dir = File(".")
@TaskAction
fun action() {
println("CustomTask.dir: ${dir.absolutePath}")
}
}
tasks.create<CustomTask>("debug") {
//dir = File(".gradle") // Script compilation fails if I uncomment this line
}
tasks.create("traverseDir") {
doLast {
traverseDir(File("gradle/wrapper/gradle-wrapper.jar"))
}
}
fun traverseDir(file: File) {
var dir: File? = file.parentFile
while (dir != null) {
println(dir)
dir = dir.parentFile
}
}
没有任务配置(表示注释的目录分配)的./gradlew debug traverseDir
输出:
> Task :debug
CustomTask.dir: /home/.../gradle-kotlin_dsl-smart_cast_error/.
> Task :traverseDir
gradle/wrapper
gradle
BUILD SUCCESSFUL in 0s
2 actionable tasks: 2 executed
带有任务配置(表示未注释的目录分配)的./gradlew debug traverseDir
的输出:
> Configure project :
e: /home/.../gradle-kotlin_dsl-smart_cast_error/build.gradle.kts:32:11: Smart cast to 'File' is impossible, because 'dir' is a local variable that is captured by a changing closure
FAILURE: Build failed with an exception.
* Where:
Build file '/home/.../gradle-kotlin_dsl-smart_cast_error/build.gradle.kts' line: 32
* What went wrong:
Script compilation error:
Line 32: dir = dir.parentFile
^ Smart cast to 'File' is impossible, because 'dir' is a local variable that is captured by a changing closure
1 error
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 0s
这两个任务没有相互联系(除了它们是在同一buildscript文件中定义的),但是当我尝试配置自定义任务的实例(即取消注释dir = ...
行)时,该构建由于traverseDir函数中看似不相关的脚本编译错误而失败。
更奇怪:
dir
变量(即重命名为dir_
),则不会发生该错误-然后构建成功。dir = dir.parentFile
更改为dir = dir?.parentFile
使构建成功。为什么会这样?
./gradlew --version
的输出:
------------------------------------------------------------
Gradle 4.10
------------------------------------------------------------
Build time: 2018-08-27 18:35:06 UTC
Revision: ee3751ed9f2034effc1f0072c2b2ee74b5dce67d
Kotlin DSL: 1.0-rc-3
Kotlin: 1.2.60
Groovy: 2.4.15
Ant: Apache Ant(TM) version 1.9.11 compiled on March 23 2018
JVM: 1.8.0_181 (Oracle Corporation 25.181-b13)
OS: Linux 4.15.0-33-generic amd64
更新:
这似乎是一个错误,我在以下位置创建了问题: