I hope someone can explain this to me.
I was moving some code from a Gradle build file into a Gradle plugin. Below are two code snippes calling the same from
function (based on Ideas indexing) I noticed that there are some strange differences between how the apis can be used in those two contexts.
I know that Gradle is adding some extra syntax suger around the build files which is why I need to manually cast the task in the Plugin.kt
file, but I cannot find anything that explains why from in context of the Build file has this
as context where in the plugin the function uses it
to access the into
function.
It is not just Idea that reports this, running Gradle also shows that it must be like this.
I assume this is something special to Kotlin's way of handling the Action
interface in different contexts:
- kts file (No wrapping class)
- kt file (with class)
Here are the two sampleshostedStaticFiles
is gradle configuration that will be used to configure web frontend from a separate build.
build.gradle.kts
tasks.getByName<ProcessResources>("processResources") {
this.from(hostedStaticFiles) {
this@from.into("static") // <-- Note use of this here
}
}
Plugin.kt
project.tasks.getByName("processResources").let<Task, ProcessResources> {
if (it !is ProcessResources) {
throw IllegalStateException("The processResources task in Project is not of type ${ProcessResources::class.java}")
}
it
}.apply {
dependsOn(hostedStaticFiles)
this@apply.from(hostedStaticFiles) { it -> // <-- Note use of it here and below
it.into("static")
}
}
dependencies {
hostedStaticFiles(project("client"))
}
I hobe someone can point me to an explanation or preferably documentation on why this behaves this way :)
Gradle version 7.4.1
###################
After getting the answer from @Joffrey I updated my buildSrc/build.gradle.kts
with the below plugin configuration and it all started working as expected.
plugins {
`java-gradle-plugin`
`kotlin-dsl`
}
1条答案
按热度按时间yhuiod9q1#
Gradle在某些函数类型(如
Action
)上使用HasImplicitReceiver注解,因此您可以使用this
代替it
。在Kotlin构建脚本(
.gradle.kts
文件)中,您会自动受益于此,因为用于编译脚本的Kotlin编译器已经正确配置。然而,在自定义插件项目中,您可以控制构建,您需要自己应用kotlin-dsl
插件。正如文档中提到的,它会为您做一些事情,包括: