is there a shortcut for `val a = try { myfun()} } ...
# announcements
r
is there a shortcut for
val a = try { myfun()} } catch(T: Throwable){ null }
b
Using Arrow (arrow-kt.io): val a = Try.invoke(::myfun).orNull()
a
i haven’t used it, and I think it uses coroutines(?), but maybe https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/run-catching.html would be helpful
r
I was hoping for something like that but from the std-lib 🙂
@arekolek I am using kotlin 1.2.x but good to know
d
I use this ( or other variants, depending on the use case )
Copy code
fun <T: Any?> handle( default: T? = null, block: () -> T ) : T? {
    return  try {
        block()
    } catch ( t: Throwable ) {
        default
    }
}
m
Copy code
val a = runCatching { myfun() }.getOrNull()
☝🏻 1
d
Looks like overkill a
runCatching
for me
m
Why overkill? It does exactly what was asked for and in the non-error case it has no overhead due to use of
inline class
.
d
He's using Kotlin 1.2, where there isn't any
runCatching
yet. But I've upgraded a few projects to 1.3, and it went smoothly, and there are pretty handy changes that made it worth it... runCatching is especially interesting when accumulating `Result`s and acing on them later.
d
@Marc Knaup there is no overhead as you said, but I would use it for a more complex purpose. I'm not said it's wrong to use it, it's just my personal feeling