即使您省略 return
语句,lambda 的最后一行似乎总是返回该值。这个对吗?它是否记录在任何地方?
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 的最后一条语句是表达式,则将其视为返回值。
这里是 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
block ,这些语句本身就是表达式:
val foo = if (bar) {
doSomething()
baz
} else {
doSomethingElse()
qux
}
参见:examples for when
and try
-catch
.
因此,lambda 在这方面与语言结构是一致的。
如果你想在一个 lambda 表达式中创建一个显式的 return
语句,使用 return@label
syntax (还有 another answer with examples )。相反,未标记的 return
与最近的 fun
一起工作(忽略 lambdas),因此只能出现在 inlined 的那些 lambdas 中。 .
有一个 language proposal为代码块中的发射值添加特殊语法,但它被拒绝了。
关于kotlin - Kotlin 中 lambda 的隐式返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41620937/