gradle - Kotlin 无法将 gradle 的 Action 类转换为 lambda

标签 gradle kotlin gradle-kotlin-dsl

所以,虽然这是一个针对 gradle 特定问题的 kotlin-dsl,但我认为它总体上适用于 kotlin 语言本身,所以我不会使用该标签。

在 gradle API 中,类 Action<T>定义为:

@HasImplicitReceiver
public interface Action<T> {
    /**
     * Performs this action against the given object.
     *
     * @param t The object to perform the action on.
     */
    void execute(T t);
 }

所以理想情况下,这应该在 kotlin 中工作(因为它是一个带有 SAM 的类):

val x : Action<String> = {
    println(">> ${it.trim(0)}")
    Unit
}

但是我收到以下两个错误:

Unresolved reference it
Expected Action<String> but found () -> Unit

Fwiw,甚至Action<String> = { input: String -> ... }不起作用。

现在这是真正有趣的部分。如果我在 IntelliJ 中执行以下操作(顺便说一句,有效):

object : Action<String> {
    override fun execute(t: String?) {
        ...
    }
}

IntelliJ 弹出建议 Convert to lambda ,当我这样做时,我得到:

val x = Action<String> {
}

哪个更好,但是it仍未解决。现在指定它:

val x = Action<String> { input -> ... }

给出以下错误 Could not infer type for inputExpected no parameters 。有人可以帮我解决发生的事情吗?

最佳答案

这是因为gradle中的Action类被注释为HasImplicitReceiver 。来自文档:

Marks a SAM interface as a target for lambda expressions / closures where the single parameter is passed as the implicit receiver of the invocation (this in Kotlin, delegate in Groovy) as if the lambda expression was an extension method of the parameter type.

(强调我的)

因此,以下代码可以正常编译:

val x = Action<String> {
    println(">> ${this.trim()}")
}

您甚至可以只写 ${trim()} 并省略前面的 this

关于gradle - Kotlin 无法将 gradle 的 Action 类转换为 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47908148/

相关文章:

kotlin - 如何使用Gradle Kotlin DSL向所有 jar 添加前缀

gradle - 人为因素:无法持久保存文件;状态码:404/Gradle

gradle - STS/Eclipse中对Gradle上下文敏感的支持

groovy - 从项目中读取Gradle路径

android - 使用消息 "method not allowed here"改造响应代码 405

android-studio - Unresolved reference : BR (Android Studio)

android - 如何在 Android Studio Bumblebee 中添加项目级依赖类路径

java - Spring Boot JPA @Query 更新不起作用

gradle - 设置Gradle自定义任务输入和输出

gradle - 使用 gradle kotlin-dsl 覆盖 spring boot 依赖版本