Member-only story
Stop Using Kotlin’s Result in Your Application Code!
A deep dive into why Result
is not ideal for handling errors in application code and how Either
offers a better approach.
A couple of days ago, I had a discussion about Kotlin’s Result
type vs. arrow-kt
's Either
. There are upsides and downsides to both, but I am a big fan of Either
over Result
, mainly because I think the design of Result
comes with some flaws. Before we discuss these flaws, let’s take a step back and look at Result
and why one might want to use it.
Understanding Result
Result
is a class from the Kotlin standard library. The KDoc states that it is:
A discriminated union that encapsulates a successful outcome with a value of type T or a failure with an arbitrary Throwable exception.
In other words, we can use Result
in places where we would throw an exception, with the difference that returning a Result
will not change the control flow as a thrown exception does.
Take a look at this example:
fun unsafeParseInt(str: String): Int {
return str.toInt() // This throws NumberFormatException for invalid input
}
fun main() {
val numbers = listOf("1", "2", "abc", "4")
val parsedNumbers =…