Kotlin 中 lambda 的隐式返回 [英] Implicit return from lambda in Kotlin

查看:33
本文介绍了Kotlin 中 lambda 的隐式返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎即使省略了 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):

我们可以使用限定返回 语法.否则,隐式返回最后一个表达式的值.因此,以下两个片段是等效的:

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(这就是为什么没有三元运算符)whentry-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 
}

另见:whentry-catch.

因此,Lambda 在这方面与语言结构是一致的.

So, lambdas are consistent with the language constructs in this respect.

如果您想在 lambda 中创建显式的 return 语句,请使用 return@label 语法(还有,另一个带有示例的答案).相反,未标记的 return 与最近的 fun 一起使用(忽略 lambdas),因此只能出现在那些 内联.

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.

这篇关于Kotlin 中 lambda 的隐式返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆