Search code examples
scalascala-cats

Convert Type1: EitherT[Future, String, Int] to Type2: EitherT[Future, String, Option[Int]] while all the Left in Type1 become Right(None) in Type2


Suppose I have a:

val origin_left: EitherT[Future, String, Int] = EitherT.fromEither[Future](Left("some-error"))
val origin_right: EitherT[Future, String, Int] = EitherT.fromEither[Future](Right(100))

I want to convert it to

val converted_left: EitherT[Future, String, Option[Int]] = EitherT.fromEither[Future](Right(None))
val converted_right: EitherT[Future, String, Option[Int]] = EitherT.fromEither[Future](Right(Some(100)))

The reason I want to do this is if you have a Left, the for comprehension will end immediately. So I want to convert the Left into a Right(None) to continue the for comprehension.


Solution

  • After some tries, I found the answer (using fold):

    val converted = EitherT(origin.fold(_ => Right(None), num => Right(Some(num))))