我有一个类型为
val input: Future[Seq[Either[ErrorClass, Seq[WidgetCampaign]]]] = ???我希望遍历此输入并删除所有重复的WidgetCampaign,并将输出返回为
val result: Future[Either[ErrorClass,Set[WidgetCampaign]]] = ???我如何才能做到这一点?
发布于 2020-06-10 06:16:05
首先,可以使用map调用在Future中完成所有处理:
input.map(process)所以问题是要编写一个在Seq[Either[ErrorClass, Seq[WidgetCampaign]]和Either[ErrorClass, Set[WidgetCampaign]]之间进行转换的process函数。
首先创建几个类型别名,以使代码的其余部分更加简洁。
type InType = Either[ErrorClass, Seq[WidgetCampaign]]
type OutType = Either[ErrorClass, Set[WidgetCampaign]]这个过程本身可以通过一个笨拙的flatMap调用来完成,但是一个简单的递归函数可能是最好的:
def process(input: Seq[InType]): OutType = {
@annotation.tailrec
def loop(rem: List[InType], res: Set[WidgetCampaign]): OutType =
rem match {
case Nil => // Stop when no more elements to process
Right(res)
case Left(e) :: _ => // Stop on first error
Left(e)
case Right(s) :: tail => // Add this Seq to the result and loop
loop(tail, res ++ s)
}
loop(input.toList, Set.empty[WidgetCampaign])
}这是递归逻辑的标准模式,其中递归函数本身被包装在外部函数中。为了提高效率,内部函数是尾递归的,中间结果通过递归调用向下传递。
输入被转换为List以使模式匹配变得更容易。
这是未经测试的,但它可以编译,所以这是一个开始...
https://stackoverflow.com/questions/62292283
复制相似问题