鉴于eithers的序列Seq[Either[String,A]]与Left作为一个错误消息.我想获得一个Either[String,Seq[A]]在那里我得到了Right(这将是一个Seq[A]),如果序列的所有元素Right.如果至少有一个Left(错误消息),我想获取第一条错误消息或所有错误消息的串联.
当然你可以发布scalaz代码,但我也对不使用它的代码感兴趣.
我改变了标题,最初要求Either[Seq[A],Seq[B]]反映信息的正文.
我有一个任何一个列表,它代表错误:
type ErrorType = List[String]
type FailFast[A] = Either[ErrorType, A]
import cats.syntax.either._
val l = List(1.asRight[ErrorType], 5.asRight[ErrorType])
Run Code Online (Sandbox Code Playgroud)
如果所有这些都正确,我想获得 [A] 的列表,在这种情况下 - List[Int]
如果有任何Either剩余,我想合并所有错误并返回它。
我在 [ How to reduce a Seq[Either[A,B]] to a Each[A,Seq[B]]找到了一个类似的主题
但那是很久以前的事了。例如,其中一个答案提供使用partitionMap,我目前找不到。可能有更好、更优雅的解决方案。使用 scala-cats 的例子会很棒。
我想如何使用它:
for {
listWithEihers <- someFunction
//if this list contains one or more errors, return Left[List[String]]
//if everything is fine, convert it to:
correctItems <- //returns list of List[Int] as right
} yield correctItems
Run Code Online (Sandbox Code Playgroud)
这个 for-comprehension 的返回类型必须是:
Either[List[String], List[Int]]
Run Code Online (Sandbox Code Playgroud) 有Futures一种简单的方法可以转换Seq[Future]为Future[Seq]:
Future.sequence(seqOfFutures)
我找不到与 . 类似的东西Try。
它适用于foldLeft但我真正喜欢的会有类似的东西Try.sequence(seqOfTry)。
不提供这样的功能有什么原因吗?
如何正确完成此操作?
语义:
成功的价值观列表:Success(Seq(1,2,3,4))
失败有两种可能:
拳头失败Failure并返回。这是通过这个问题处理的:listtryt-to-trylistt-in-scala
收集所有内容Failures并返回“复合”失败。
对于“复合”故障还有解决方案吗?