How to convert `NonEmptyList [Either [Error, User]]` to `Either [Error, NonEmptyList [User]] 'with cats?

I use cats , I wonder how to handle it:

val data = NonEmptyList[Either[Error, User]] 

to

 val target: Either[Error, NonEmptyList[User]] = howToConvert(data) 
+5
source share
1 answer

Usually, when you want to turn type constructors inside out, you're probably looking for sequence . If you included -Ypartial-unification in Scala> = 2.11.9, you can just let the compiler do everything:

 data.sequence 

Otherwise:

 type EitherError[A] = Either[Error, A] data.sequence[EitherError, User] 

Or if you have type lambda plugin :

 data.sequence[Either[Error, ?], User] 

Or if you don’t have a plugin but don’t like type aliases:

 data.sequence[({type L[A] = Either[Error, A]})#L, User] 

It will do the expected thing, either returning the first error, or all users if there is no error. If we pretend that users are int and errors are strings:

 scala> import cats.data.NonEmptyList, cats.implicits._ import cats.data.NonEmptyList import cats.implicits._ scala> val data: NonEmptyList[Either[Error, User]] = NonEmptyList.of(Right(2), Left("error1"), Right(4)) data: cats.data.NonEmptyList[Either[Error,User]] = NonEmptyList(Right(2), Left(error1), Right(4)) scala> data.sequence res4: Either[Error,cats.data.NonEmptyList[User]] = Left(error1) 
+5
source

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


All Articles