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

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

    val list = List(Left("x"),Right(2), Right(4))
    val strings = for (Left(x) <- list) yield(x)
    val result = if (strings.isEmpty) Right(for (Right(x) <- list) yield(x)) 
                 else Left(strings)
    

提交回复
热议问题