Best way to turn a Lists of Eithers into an Either of Lists?

前端 未结 9 1873
轮回少年
轮回少年 2020-12-13 13:14

I have some code like the below, where I have a list of Eithers, and I want to turn it into an Either of Lists ... in particular (in this case), if there are any Lefts in th

9条回答
  •  情书的邮戳
    2020-12-13 13:41

    I kind of don't want any karma for this as it's a merge of Chris's answer and Viktor's from here.. but here's an alternative:

    def split[CC[X] <: Traversable[X], A, B](xs: CC[Either[A, B]])
       (implicit bfa: CanBuildFrom[Nothing, A, CC[A]], bfb: CanBuildFrom[Nothing, B, CC[B]]) : (CC[A], CC[B]) =
      xs.foldLeft((bfa(), bfb())) {
        case ((as, bs), l@Left(a)) => (as += a, bs)
        case ((as, bs), r@Right(b)) => (as, bs += b)
      } match {
        case (as, bs) => (as.result(), bs.result())
      }
    

    Example:

    scala> val eithers: List[Either[String, Int]] = List(Left("Hi"), Right(1))
    eithers: List[Either[String,Int]] = List(Left(Hi), Right(1))
    
    scala> split(eithers)
    res0: (List[String], List[Int]) = (List(Hi),List(1))
    

提交回复
热议问题