简体   繁体   中英

Scala Future and Either Transformation

I have a variable of type

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

I want to traverse this input and remove all duplicates WidgetCampaign and return the output as

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

How can I achieve this?

Firstly, the processing can all be done inside the Future using a map call:

input.map(process)

So the problem is to write a process function that converts between Seq[Either[ErrorClass, Seq[WidgetCampaign]] and Either[ErrorClass, Set[WidgetCampaign]] .

Start by making a couple of type aliases to make the rest of the code cleaner.

type InType = Either[ErrorClass, Seq[WidgetCampaign]]
type OutType = Either[ErrorClass, Set[WidgetCampaign]]

The process itself can be done with an awkward flatMap call, but a simple recursive function is probably best:

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])
}

This is a standard pattern for recursive logic where the recursive function itself is wrapped in an outer function. The inner function is then tail-recursive for efficiency, with the intermediate result being passed down through the recursive call.

The input is converted to a List to make pattern matching easier.

This is untested, but it compiles so that's a start...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM