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

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

在gradle API中,类Action被定义为:

 @HasImplicitReceiver public interface Action { /** * 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 = { println(">> ${it.trim(0)}") Unit } 

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

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

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

现在这是真正耐人寻味的部分。 如果我在IntelliJ(这顺便说一下,工程)做以下事情:

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

IntelliJpopup建议Convert to lambda ,当我这样做,我得到:

 val x = Action { } 

哪个更好,但还是没有解决。 现在指定它:

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

给出以下错误Could not infer type for inputExpected no parameters 。 有人可以帮助我发生什么事吗?

这是因为Gradle中的Action类是用HasImplicitReceiver注解的。 从文档:

将一个SAM接口标记为lambdaexpression式/闭包的目标,其中单个参数作为调用的隐式接收方在Kotlin中 ,Groovy中的delegate传递 ,好像lambdaexpression式是参数types的扩展方法

(重点是我的)

所以,下面的编译就好了:

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

你甚至可以写${trim()}并在它前面省略this

您需要使用类名称引用该函数,如:

 val x: Action = Action { println(it) }