Reputation: 798
I am trying to create an infix function to my project to check the result of a try catch function.
I saw a solution out there but is passing the block as parameter and running that block inside the tryOrNull function like that.
fun <T : Any> tryOrNull(body: () -> T?): T? {
//the body returns T? so that you can give up the work by returning null
return try {
body()
} catch (e: Exception) {
e.printStackTrace()
null
}
}
and using like that
fun parse(): MyData? {
return tryOrNull { parse1() }
?: tryOrNull { parse2() }
?: tryOrNull { parse3() }
}
this info I saw here
But I would like to know if there is a different way to this something like that
fun parse(): MyData? {
return parse().tryOrNull() ?: false
}
I would like to create an infix or extension function but I don't know how to manage at all. Thanks!.
Upvotes: 2
Views: 280
Reputation: 93902
The syntax you suggested (parse().tryOrNull()
) would be impossible because parse()
would be called and return a result before it reached tryOrNull()
.
However,
::parse.tryOrNull()
or
{ parse() }.tryOrNull()
are possible if you write your utility function like this:
inline fun <T> (() -> T).tryOrNull(): T? = runCatching(this)
.also { it.exceptionOrNull()?.printStackTrace() }
.getOrNull()
But I think the original syntax you showed is clearer. It makes more semantic sense to see the thing you are calling wrapped in the tryOrNull
call instead of tacking tryOrNull
on like an afterthought.
Upvotes: 2