How to turn `Either [Error, Option [Either [Error, Account]]] 'to` Either [Error, Option [Account]]' with codes like levelvel?

I use cats , I wonder how to handle it.

WITH

val data = Either[Error, Option[Either[Error, Account]]]

to

val target: Either[Error, Option[Account]] = howToConvert(data)

If any happens Error, the result will be Left(error)with the first error that appears.

Now I can do it with

data match {
  case Left(e) => Left(e)
  case Right(Some(Right(y))) => Right(Some(y))
  case Right(Some(Left(e))) => Left(e)
  case Right(None) => Right(None)
}

But I'm looking for an easy way

+4
source share
2 answers

The easiest way to do this is sequenceinside Option, so that you receive Either[Error, Either[Error, Option[Account]]]and then smooth it. With cat syntax, this is very simple:

import cats.implicits._

val target: Either[Error, Option[Account]] =
  data.flatMap(_.sequence)

, sequence "", Option[Either[Error, Account]] Either[Error, Option[Account]].

+6

"" , (Scala 2.12),

val target: Either[Error, Option[Account]] =
    data.flatMap(_.map(_.map(Some(_))).getOrElse(Right(None)))
+1

Source: https://habr.com/ru/post/1692182/


All Articles