簡體   English   中英

如何用貓將`NonEmptyList [Either [Error,User]]`轉換為`Either [Error,NonEmptyList [User]]`?

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

我正在使用 ,想知道如何使用它來轉換數據:

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

val target: Either[Error, NonEmptyList[User]] = howToConvert(data)

通常,當您要把類型構造函數的內容翻過來時,您可能正在尋找sequence 如果在Scala> = 2.11.9中啟用了-Ypartial-unification ,則可以讓編譯器推斷所有內容:

data.sequence

除此以外:

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

或者,如果您有lambda類型的插件

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

或者,如果您沒有插件,但是不喜歡輸入別名:

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

它將執行返回第一個錯誤或沒有錯誤的所有用戶的預期操作。 如果我們假裝用戶是整數,而錯誤是字符串:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM