y
09/07/2022, 8:22 AMtry-catch
idiomatic in Kotlin?Sam
09/07/2022, 8:26 AMStephan Schroeder
09/07/2022, 8:52 AMxOrNull
functions for every x
function that returns a non-nullable value and throws an exception.
But is try-catch
inside those equivalent or less ideomatic
@Throws(...)
fun x(...): X = ...
fun xOrNull(...): X? = try {
x(...)
} catch (e: Throwable) {
null
}
than runCatching
?
fun xOrNull(...): X? = runCatching {
x(...)
}.getOrNull()
Sam
09/07/2022, 9:13 AMrunCatching
, `try`/`catch` is the more idiomatic choice. runCatching
is intended specifically for those use cases where wrapping an execution into a Result
enables functional style code that wouldn’t be possible without it. For general use, it actually has some disadvantages, like making it harder to be specific about which errors you want to catch. More info in the KEEP: https://github.com/Kotlin/KEEP/blob/master/proposals/stdlib/result.mdy
09/07/2022, 9:55 AMtry-catch
here, right?cd1
09/07/2022, 10:20 AM