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)whentry-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.

Kotlin相关问答推荐

只能在元素区域中点击的Jetpack Compose列

将基于注册的服务转换为流

如何编写带有依赖项的自定义Kotlin串行化程序?

如何避免使用公共类实现内部接口

Kotlin:我可以将函数分配给 main 的伴随对象中的变量吗?

如何在 Kotlin 中不受约束?

有没有办法重用 Job 实例?

从列表中的每个对象中 Select 属性

Kotlin 1.2.21 + SimpleXml 2.3.0 - consume List error (must mark set get method)

将 Firebase 数据快照反序列化为 Kotlin 数据类

为什么 Dialog 没有 NavController [Missing]?

Firebase 权限被拒绝

Kotlin 的 Double.toInt() 中使用了哪种方法,舍入还是截断?

如何限制kotlin协程的最大并发性

内联 onFocusChange kotlin

如何在Kotlin中将字符串转换为InputStream?

内联 Kotlin 方法没有覆盖报告

如何在 IntelliJ IDEA 中禁用粘贴时将 Java 转换为 Kotlin?

如何在 Kotlin 中定义新的运算符?

如何判断数据是否插入到房间数据库中