Scala未来与任何转换

问题描述 投票:0回答:1

我有一个类型的变量

val input: Future[Seq[Either[ErrorClass, Seq[WidgetCampaign]]]] = ???

我想遍历此输入并删除所有重复项WidgetCampaign,然后将输出返回为

val result: Future[Either[ErrorClass,Set[WidgetCampaign]]] = ???

我该如何实现?

scala future seq either
1个回答
0
投票

首先,可以使用Future调用在map内部完成所有处理:

input.map(process)

所以问题是编写一个在processSeq[Either[ErrorClass, Seq[WidgetCampaign]]之间转换的Either[ErrorClass, Set[WidgetCampaign]]函数。

首先创建几个类型别名,以使其余代码更简洁。

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以使模式匹配更加容易。

未经测试,但可以编译,因此是一个开始...

© www.soinside.com 2019 - 2024. All rights reserved.