Add Either.recover?

I use Either to indicate Either[Error, Ok] as I believe is common usage, and frequently find that I do the following:

val result: Either[MyError, MyActualResult] = ... // some computation
result.fold(err => recover(err), r => r) // => MyActualResult

This would be neatly simplified by adding a dedicated recover method to the Either class itself:

  def recover[B1 >: B](fa: A => B1): B = this match {
    case Right(b) => b
    case Left(a) => fa(a)
  }

Toughts?

3 Likes

Might look into Cats, as this very much resembles cats.ApplicativeError#handleError, which is defined for Either.

If you prefer Scalaz, they probably have an equivalent (I just don’t know what it is off the top of my head).

I’m not sure if I like the name “recover”, as it pushes the left result into an error result too much, but i do like having the method. Maybe not over a mapLeft though.

Side note, an alternative implementation is def recover[B1 > B](f: A => B1): B1 = swap.map(f).merge which is IMO just long enough to make a convenience method useful.

If mapLeft existed, it would be mapLeft(f).merge, which is IMO short enough not to need a convenience method.

Generally, we plan to ship Scala 3 with the standard library of Scala 2.13, so that we can assure binary interop between components written in both versions. That means that any changes to the standard library that break binary compatibility will have to wait a bit longer. There will probably be a small add-on library that is Scala 3 only, but we want to keep it minimal, at least for Scala 3.0.

4 Likes