Hello. Is there a way to transform an `Either` suc...
# arrow
c
Hello. Is there a way to transform an
Either
such that if
Left
meets some specific condition (i.e. filter out some error code that should not throw an error) the downstream Either via the fold operation gets routed to
ifRight
? I did something like this (where Either<List<MyErrors>, <Data>>):
Copy code
return someService()
            .map { it.toEither().mapLeft {
                it.filter { it.code != "some-failure-code" }
            } }
But all that does in return an empty list of MyErrors to the downstream fold’s isLeft.
s
If you want to convert a
Left
potentially to a
Right
depending on its value, you can make use of
handleErrorWith
- https://arrow-kt.io/docs/arrow/typeclasses/applicativeerror/#kindf-ahandleerrorwith
in your example, something like:
Copy code
someService()
  .map { it.toEither().handleErrorWith {
    when (val errs = it.filter { it.code != "some-failure-code" }) {
      errs.isEmpty() -> Right(Unit) // or some other value to recover to
      else -> Left(errs)
    }
  } }
☝️ 2
s
Yes, at the very end of your code you could turn a
Left
into
Right
by inspecting
Left
and returning any arbitrary
Either
using
handleErrorWith
. Or use
handleError
if you only want to return a
Right
.
Copy code
val either: Either<String, Int> = ...

either.handleErrorWith { str ->
  Either.catch { str.toInt() }
}

either.handleError { str -> 0 }
c
Awesome. Thank you! 🙇