【问题标题】:Is there conditional try statement in Kotlin like in Swift?Kotlin 中是否有条件 try 语句,就像在 Swift 中一样?
【发布时间】:2021-04-10 17:26:00
【问题描述】:

每当我想做一些简单的事情时,我发现每次在 Kotlin 中编写丑陋的 try/catch 语句非常烦人:

val el = collection.filter{condition}.first
el?.field // this is not going to work since 'first' can throw an exception
    or
val l = someString.toLong() // This can throw NumberFormatException

有一个不错的尝试吗? Swift 中的声明:

let el = try? expression
el?.field // this will work like a charm 

在 Kotlin 中有这样的东西吗?

【问题讨论】:

    标签: android kotlin exception


    【解决方案1】:
    val el = collection.firstOrNull{condition}
    el?.field
    

    你总是可以创建自己的函数

    inline fun <R> expressionOrNull(block: () -> R): R? {
        return try {
            block()
        } catch (e: Throwable) {
            null
        }
    }
    
    val el = expressionOrNull { expression }
    el?.field
    

    或者你可以使用标准库

    val el = runCatching { expression }.getOrNull()
    el?.field
    

    【讨论】:

    • 谢谢,这真是太好了。第二个转换为 Long 呢?
    • someString.toLongOrNull() ?
    • 是的,我打字太早了。谢谢。不过,我想试试?更通用,因为它可以处理任何异常
    • 我可能会使用这种函数方法。再次感谢。
    • 这不是使用扩展方法的合适案例吗?
    【解决方案2】:

    有关内置解决方案,请参阅 IR42's answer。但是,如果您不喜欢这些,也可以轻松设置自己的:

    fun <T> tryOrNull(block: () -> T): T? {
      return try {
        block()
      } catch (t: Throwable) {
        null
      }
    }
    
    fun main() {
      val foo = tryOrNull { listOf(1).first() }
      val bar = tryOrNull { emptyList<Int>().first() }
      
      println("foo: $foo, bar: $bar")
    }
    

    输出为foo: 1, bar: null,因为emptyList&lt;Int&gt;().first() 导致异常,所以tryOrNull() 的计算结果为null

    就个人而言,我不是粉丝。异常是您的方法明确忽略的非常有用的信息。但是,这是可以做到的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-22
      • 2017-04-02
      • 1970-01-01
      • 2011-01-06
      • 2013-03-23
      • 2019-03-02
      • 1970-01-01
      • 2014-02-03
      相关资源
      最近更新 更多