问题描述
我可以在括号之外写一个lambda表达式,但是我不能用名字来表达它。我尝试了很多方法:
val plus3:(Int,Int,Int) - > Int = {a,b, (应用3(1,2,3){a,b,c-> a + b + c})// OK
println(apply3 (1,2,3){plus3})//类型不匹配。 Required:Int,Found:(Int,Int,Int) - > Int
println(apply3(1,2,3){(plus3)})//类型不匹配。 Required:Int,Found:(Int,Int,Int) - > Int
println(apply3(1,2,3)plus3)//未解析的引用
println(apply3(1,2,3 ){plus3()})//在闭包中捕获的值
println(apply3(1,2,3){(plus3)()})//在闭包中捕获的值
在那里放置一个名字的语法是什么(在括号之外)?
我不知道为什么,但在中没有一个词主题。它说,我们可以把lambda放在那里,但不是关于表示lambda的变量或常量的一个字。
是的,那里是:
plus3
是一个标识符而不是一个lambda表达式,因此您不能在括号外指定它。
您的意思是您传递 {plus3}
时的错误消息?按照Kotlin规则 {plus3}
是一个忽略其参数(如果有的话)并返回 plus3
的lambda。所以这个规则适用,并且 apply3(1,2,3){plus3}
的含义与 apply3(1,2,3,{plus3 })
。
正好相反:它希望看到一个 Int
作为lambda的返回值,并且看到 plus3
,它是(Int,Int,Int) - > Int
。
这恰恰是我的观点:规则纯粹是句法,它在编译器知道任何有关<$ c $的类型或值的应用程序c> plus3 ,所以它不知道或关心这个值是否是lambda。
规则可以代替
在这种情况下 apply3(1,2,3)plus3
会起作用。但它没有。
I can write a lambda expression outside of parenthesis, but I cannot put it there by name. I have tried many ways:
val plus3: (Int,Int,Int)->Int = {a,b,c->a+b+c}
println(apply3(1,2,3){a,b,c->a+b+c}) // OK
println(apply3(1,2,3){plus3}) // Type mismatch. Required: Int, Found: (Int,Int,Int)->Int
println(apply3(1,2,3){(plus3)}) // Type mismatch. Required: Int, Found: (Int,Int,Int)->Int
println(apply3(1,2,3)plus3) // unresolved reference
println(apply3(1,2,3){plus3()}) // value captured in a closure
println(apply3(1,2,3){(plus3)()}) // value captured in a closure
What is the syntax to put a name there (outside of parenthesis)?
I don't know why, but in the documentation there is not a word on the theme. It says we could put lambda there, but not a word about a variable or constant that denotes that lambda.
Yes, there is:
plus3
is an identifier and not a lambda expression, so you can't specify it outside of parentheses.
You mean the error messages when you pass { plus3 }
? By Kotlin rules { plus3 }
is a lambda which ignores its argument (if any) and returns plus3
. So the rule applies, and apply3(1,2,3){plus3}
means the same as apply3(1,2,3,{plus3})
.
Exactly the opposite: it expects to see an Int
as the return value of the lambda and sees plus3
which is (Int,Int,Int) -> Int
.
That was exactly my point: the rule is purely syntactic, it's applied before the compiler knows anything about type or value of plus3
, and so it doesn't know or care whether this value happens to be a lambda.
The rule could instead say
in which case apply3(1,2,3) plus3
would work. But it doesn't.
这篇关于我可以使用lambda的名称作为传递给“括号外的参数”的参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!