lambda的最后一行似乎总是返回该值,即使省略了return
语句.对吗?有记录在案吗?
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的最后一行似乎总是返回该值,即使省略了return
语句.对吗?有记录在案吗?
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]
}
Yes, this is correct, if the last statement of a lambda is an expression, it is considered its return value.
这里是what the reference says(谢谢@KirillRakhman):
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
(that's why there's no ternary operator)、when
和try
-catch
块也是如此,这些语句本身就是表达式:
val foo = if (bar) {
doSomething()
baz
} else {
doSomethingElse()
qux
}
另请参阅:examples for when
and try
-catch
.
So, lambdas are consistent with the language constructs in this respect.
如果要在lambda中显式地使用return
语句,请使用return@label
syntax(也就是another answer with examples).相反,无标签return
与最接近的fun
(忽略lambda)一起工作,因此只能出现在inlined的lambda中.
There was a language proposal to add special syntax for emitting a value from a code block, but it was rejected.