【发布时间】:2018-02-12 05:03:13
【问题描述】:
我正在寻找一种惯用的方式来返回 Kotlin 中的变量(如果不是 null)。例如,我想要这样的东西:
for (item in list) {
getNullableValue(item).? let {
return it
}
}
但不可能在 Kotlin 中的 let 块内返回。
有没有一种无需这样做的好方法:
for (item in list) {
val nullableValue = getNullableValue(item)
if (nullableValue != null) {
return nullableValue
}
}
【问题讨论】:
-
可以从
let{}到return。您的两个 sn-ps 都是正确的,并且做的事情完全相同。
标签: kotlin