相同的GradleKotlin副本,从构建文件(kt)调用时,从'API使用' it ',从Pluign(kt)调用时,从`this'

pbpqsu0x  于 2022-12-13  发布在  Kotlin
关注(0)|答案(1)|浏览(180)

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 samples
hostedStaticFiles 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`
}
yhuiod9q

yhuiod9q1#

Gradle在某些函数类型(如Action)上使用HasImplicitReceiver注解,因此您可以使用this代替it
在Kotlin构建脚本(.gradle.kts文件)中,您会自动受益于此,因为用于编译脚本的Kotlin编译器已经正确配置。然而,在自定义插件项目中,您可以控制构建,您需要自己应用kotlin-dsl插件。正如文档中提到的,它会为您做一些事情,包括:

  • 使用与Kotlin DSL脚本相同的设置来配置Kotlin编译器,以确保构建逻辑和这些脚本之间的一致性。

相关问题