Oleg Gryb
Oleg Gryb

Reputation: 5259

Is there conditional try statement in Kotlin like in Swift?

I found it extremely annoying to write ugly try/catch statements in Kotlin each time when I want to do something simple like:

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

There is a nice try? statement in Swift:

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

Is there anything like this in Kotlin?

Upvotes: 1

Views: 1373

Answers (2)

CommonsWare
CommonsWare

Reputation: 1007658

See IR42's answer for built-in solutions. However, it's fairly easy to set up your own, if you do not like those:

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")
}

The output is foo: 1, bar: null, as emptyList<Int>().first() results in an exception, so tryOrNull() evaluates to null.

Personally, I'm not a fan. Exceptions are hugely useful bits of information that your approach expressly ignores. But, it's possible to do.

Upvotes: 2

IR42
IR42

Reputation: 9732

val el = collection.firstOrNull{condition}
el?.field

You always can create your own function

inline fun <R> expressionOrNull(block: () -> R): R? {
    return try {
        block()
    } catch (e: Throwable) {
        null
    }
}

val el = expressionOrNull { expression }
el?.field

or you can use standard library

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

Upvotes: 4

Related Questions