How to split a List[Either[A, B]]

前端 未结 8 1135
南笙
南笙 2020-12-10 11:01

I want to split a List[Either[A, B]] in two lists.

Is there a better way ?

def lefts[A, B](eithers : List[Either[A, B]]) : List[A] = eit         


        
8条回答
  •  不思量自难忘°
    2020-12-10 11:24

    If scalaz is one of your dependencies I would simply use separate:

    import scalaz.std.list._
    import scalaz.std.either._
    import scalaz.syntax.monadPlus._
    
    val el : List[Either[Int, String]] = List(Left(1), Right("Success"), Left(42))
    
    scala> val (lefts, rights) = el.separate
    lefts: List[Int] = List(1, 42)
    rights: List[String] = List(Success)
    

提交回复
热议问题