为什么这个:
val runVersionSplicer by tasks.registering(type = JavaExec::class) {
classpath = sourceSets.main.runtimeClasspath // error
main = "com.concurnas.build.VersionSplicer"
}
返回:
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public val NamedDomainObjectContainer.runtimeClasspath: NamedDomainObjectProvider defined in org.gradle.kotlin.dsl
虽然这工作正常吗?
val runVersionSplicer by tasks.registering(type = JavaExec::class) {
classpath = sourceSets["main"].runtimeClasspath
main = "com.concurnas.build.VersionSplicer"
}
我知道
sourceSets.main
是这样定义的:val org.gradle.api.tasks.SourceSetContainer.`main`: NamedDomainObjectProvider<org.gradle.api.tasks.SourceSet>
get() = named<org.gradle.api.tasks.SourceSet>("main")
但是不应该替换
sourceSets["main"]
构造吗?
最佳答案
因为其中一个是提供者,另一个是对象。
sourceSets.main
使用您发现的引擎盖下的NamedDomainObjectCollection.named
。如果查看named
的javadoc,则会看到它返回以下内容:A Provider that will return the object when queried. The object may be created and configured at this point, if not already
sourceSets["main"]
直接返回源集,因为它改用NamedDomainObjectCollection.getByName
whi:The object with the given name. Never returns null.
因此,这两个是等效的:
sourceSets.main.get()
sourceSets["main"]
在Groovy中,以下内容等效:sourceSets.main
sourceSets["main"]
sourceSets.getAt("main")
这是getAt
类实现的NamedDomainObjectCollection
方法的所有不同语法。这就是为什么您在Groovy脚本中看不到很多get()
的原因,而在Kotlin DSL脚本中却看到了很多的原因。
关于kotlin - Gradle Kotlin脚本,尝试通过内置变量分配classpatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62085586/