scalaeither

What is the concise way to map error of an Either type in scala


I need to change the error type of Either in scala.

For example, I have input type Either[String, Long] and need to convert the output type as Either[Exception, Long].

Below is the sample program -

  val e2: Either[String, Long] = Left("exception 2")

  val e3:Either[Throwable, Long] = e2 match {
    case Left(ex) => Left(new Exception(ex))
    case Right(l) => Right(l)
  }

match seems bit verbose here. is there better way to do this?

Note: I'm not using advanced library like cats/zio/monix


Solution

  • You can use left projection (Either.left) with map:

    val e3 = e2.left.map(new Exception(_))