【问题标题】:Idiomatic way to return if not null in Kotlin如果在 Kotlin 中不为空,则返回的惯用方式
【发布时间】: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


【解决方案1】:

可能是这样的:

for (item in list) {
  getNullableValue(item)?.also {
    return it
  }
}

我假设需要外部循环。如果不是这种情况,Ryba 建议的解决方案应该可以工作。

【讨论】:

    【解决方案2】:

    可以从let返回,正如您在documentation中看到的那样:

    return 表达式从最近的封闭函数返回,即 foo。 (请注意,只有传递给内联函数的 lambda 表达式才支持此类非本地返回。)

    let() 是一个inline 函数,因此无论何时在let 中执行return,您都会自动从封闭函数返回,如下例所示:

    fun foo() {
        ints.forEach {
            if (it == 0) return  // nonlocal return from inside lambda directly to the caller of foo()
            print(it)
        }
     }
    

    要修改行为,可以使用“标签”:

    fun foo() {
        ints.forEach lit@ {
            if (it == 0) return@lit
            print(it)
        }
    }
    

    【讨论】:

      【解决方案3】:

      这样做的“正确”惯用方法是使用“第一种”方法。

      例子:

      val x = listOf<Int?>(null, null, 3, null, 8).first { it != null }

      他的具体例子是

      return list.first {getNullableValue(it) != null}

      【讨论】:

        【解决方案4】:

        不确定这是否会被称为惯用语,但您可以这样做:

        val nullableValue = list.find { it != null }
        if (nullableValue != null) {
            return nullableValue
        }
        

        编辑:

        根据 s1m0nw1 的回答,您可能可以将其简化为:

        list.find { it != null }?.let {
            return it
        }
        

        【讨论】:

        • 对我来说看起来很地道。可能甚至不需要 ifreturn list.find { it != null } 似乎可以解决问题。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-08
        • 2020-08-09
        • 1970-01-01
        • 2013-10-27
        • 2021-04-04
        相关资源
        最近更新 更多