[SOLVED] Reversed flatMap

As I understand it, flatMap - for example on Either passes-through Lefts and applies the mapping on the value of Rights.

Now, I wonder, if the reversed operation exists, too: Passing-through the Rights but applying the mapping on the value of Lefts.

Usecase: Given a method that returns an Either[BackendError, Value]. The result of this method should be mapped into an Either[WrappedBackendError, Value].

What I do now is:

val result: Either[BackendError, Value] = someMethod
result match {
  case Left(error) => Left(WrappedBackendError(error))
  case Right(value) => Right(value)
}

Either has method .swap which swaps right with left so that you can use the right-biased flatMap.

You mean something like that?

val result: Either[BackendError, Value] = someMethod
result.swap flatMap { error => 
  WrappedBackendError(error)
}.swap

Yeah, that is the stdlib way of solving that problem.

If you are using *cats, you can:

result.leftFlatMap(error => Left(WrappedBackendError(error)))

Or more generally:

result.handleErrorWith(error => Left(WrappedBackendError(error)))

However, it seems you really only need to:

result.leftMap(error => WrappedBackendError(error))

In the std lib, you can also go through the left projection: result.left.map(...).

1 Like

Isn’t that deprecated?
Genuine question, I really do not understand if it was deprecated or not.

There seems to have been some back and forth on that subject, but as of 2.13.2, left projection doesn’t seem to be deprecated.

1 Like

Thakn you for the clarification!