从科特林的lambda隐式返回 [英] Implicit return from lambda in Kotlin
问题描述
即使您省略了return
语句,lambda的最后一行似乎总是返回该值.这样对吗?它在任何地方都有记录吗?
It seems that the last line of a lambda always returns that value even if you omit the return
statement. Is this correct? Is it documented anywhere?
fun main(args: Array<String>) {
val nums = arrayOf(1, 2, 3)
val numsPlusOne = nums.map { it ->
val r = it + 1
r
}
// numsPlusOne = [2, 3, 4]
}
推荐答案
是的,这是正确的,如果lambda的最后一条语句是表达式,则将其视为返回值.
Yes, this is correct, if the last statement of a lambda is an expression, it is considered its return value.
以下是参考引用的内容(感谢 @KirillRakhman ):
我们可以使用限定的return 语法.否则,将隐式返回最后一个表达式的值.因此,以下两个片段是等效的:
We can explicitly return a value from the lambda using the qualified return syntax. Otherwise, the value of the last expression is implictly returned. Therefore, the two following snippets are equivalent:
ints.filter {
val shouldFilter = it > 0
shouldFilter
}
ints.filter {
val shouldFilter = it > 0
return@filter shouldFilter
}
最后一个语句的语义对于 if
也是如此没有三元运算符),when
和 try
-catch
块,这些语句本身就是表达式:
The last statement semantics is also true for if
(that's why there's no ternary operator), when
and try
-catch
blocks, and these statements are expressions themselves:
val foo = if (bar) {
doSomething()
baz
} else {
doSomethingElse()
qux
}
另请参见: when
和try
-
See also: examples for when
and try
-catch
.
因此,lambda在这方面与语言结构保持一致.
So, lambdas are consistent with the language constructs in this respect.
如果您要在lambda中做出明确的return
语句,请使用带有示例的另一个答案 ).相反,未标记的return
与最接近的fun
(忽略lambda)一起使用,因此只能在
If you want to make an explicit return
statement in a lambda, use the return@label
syntax (also, another answer with examples). Non-labeled return
, on contrary, works with the nearest fun
(ignoring lambdas) and thus can only occur in those lambdas which are inlined.
有一个语言建议为发射添加特殊语法 em>来自代码块的值,但被拒绝.
There was a language proposal to add special syntax for emitting a value from a code block, but it was rejected.
这篇关于从科特林的lambda隐式返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!