Kotlin无法将Gradle的Action类转换为lambda [英] Kotlin not able to convert gradle's Action class to a lambda
问题描述
因此,尽管这对于gradle特定问题来说是相当多的kotlin-dsl,但我认为它总体上适用于kotlin语言本身,因此我将不使用该标记.
So, while this is quite a kotlin-dsl for gradle specific issue, I think it overall applies to the kotlin language itself, so I am not going to use that tag.
在gradle API中,类Action<T>
定义为:
In the gradle API, the class Action<T>
is defined as:
@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的类):
So ideally, this should work in kotlin (because it is a class with a SAM):
val x : Action<String> = {
println(">> ${it.trim(0)}")
Unit
}
但是我收到以下两个错误:
But I get the following two errors:
Unresolved reference it
Expected Action<String> but found () -> Unit
最后,甚至Action<String> = { input: String -> ... }
都不起作用.
Fwiw, even Action<String> = { input: String -> ... }
doesn't work.
现在这是真正有趣的部分.如果我在IntelliJ中执行以下操作(顺便说一句,可行):
Now here's the really intriguing part. If I do the following in IntelliJ (which btw, works):
object : Action<String> {
override fun execute(t: String?) {
...
}
}
IntelliJ弹出建议Convert to lambda
,当我这样做时,我得到:
IntelliJ pops the suggestion Convert to lambda
, which when I do, I get:
val x = Action<String> {
}
更好,但是it
仍未解决.现在指定它:
which is better, but it
is still unresolved. Specifying it now:
val x = Action<String> { input -> ... }
出现以下错误Could not infer type for input
和Expected no parameters
.有人可以帮我解决所发生的事情吗?
gives the following errors Could not infer type for input
and Expected no parameters
. Can someone help me with what is going on?
推荐答案
This is because the Action
class in gradle is annotated with HasImplicitReceiver
. From the documentation:
将SAM接口标记为lambda表达式/闭包的目标,其中单个参数作为调用的隐式接收者传递(在Kotlin中为
this
,delegate
(在Groovy中为c9)),就好像lambda表达式是参数类型的扩展方法.
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.
(重点是我的)
因此,下面的编译就可以了:
So, the following compiles just fine:
val x = Action<String> {
println(">> ${this.trim()}")
}
您甚至可以只写${trim()}
并在其前面省略this
.
You could even just write ${trim()}
and omit the this
in front of it.
这篇关于Kotlin无法将Gradle的Action类转换为lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!