arrow-core-data / arrow.core / Try / toEither

toEither

fun toEither(): Either<Throwable, A>fun <B> toEither(onLeft: (Throwable) -> B): Either<B, A>

Convenient method to solve a common scenario when using Try. The created Try object is often converted to Either, and right after Either.mapLeft is called to translate the Throwable to a domain specific error object.

To make it easier this method takes an onLeft error domain object supplier, which does the conversion to domain error in the same time as conversion to Either occurs.

So instead of

Try {
   dangerousOperation()
}.toEither()
   .mapLeft { Error.ServerError("This really went wrong", it) }
// Left(a=Error.ServerError@3ada9e34)

One can write

Try {
   dangerousOperation()
}.toEither {
   Error.ServerError("This really went wrong", it)
}
// Left(a=Error.ServerError@4a5a3234)

Do you like Arrow?

Arrow Org
<