我正在寻找一种惯用的方式来返回Kotlin中的变量(如果不为null)。例如,我想要一些东西:
for (item in list) {
getNullableValue(item).? let {
return it
}
}
Run Code Online (Sandbox Code Playgroud)
但是不可能let在Kotlin的一个街区中返回。
是否有一个好的方法可以做到这一点而不必这样做:
for (item in list) {
val nullableValue = getNullableValue(item)
if (nullableValue != null) {
return nullableValue
}
}
Run Code Online (Sandbox Code Playgroud)
不知道这是否称为惯用语言,但是您可以这样做:
val nullableValue = list.find { it != null }
if (nullableValue != null) {
return nullableValue
}
Run Code Online (Sandbox Code Playgroud)
编辑:
根据s1m0nw1的答案,您可以将其简化为:
list.find { it != null }?.let {
return it
}
Run Code Online (Sandbox Code Playgroud)
let您可以从文档中阅读,从中返回:
return-expression从最近的封闭函数foo返回。(请注意,只有传递给内联函数的lambda表达式才支持这种非本地返回。)
let()是一个inline函数,因此只要return在内部执行let此操作,您都将自动从封闭函数返回,如本例所示:
fun foo() {
ints.forEach {
if (it == 0) return // nonlocal return from inside lambda directly to the caller of foo()
print(it)
}
}
Run Code Online (Sandbox Code Playgroud)
要修改行为,可以使用“标签”:
fun foo() {
ints.forEach lit@ {
if (it == 0) return@lit
print(it)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4077 次 |
| 最近记录: |