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

前端 未结 9 1870
轮回少年
轮回少年 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:51

    data.partition(_.isLeft) match {                            
      case (Nil,  ints) => Right(for(Right(i) <- ints) yield i)        
      case (strings, _) => Left(for(Left(s) <- strings) yield s)
    }
    

    For one pass:

    data.partition(_.isLeft) match {                            
      case (Nil,  ints) => Right(for(Right(i) <- ints.view) yield i)        
      case (strings, _) => Left(for(Left(s) <- strings.view) yield s)
    }
    

提交回复
热议问题