我需要将Iterable [Throwable,String]减少到[Throwable,Iterable [String]]。我不知道这个操作是否很常见,在Iterable特征上没有发现任何东西。所以我写了这个功能:减少Iterable [要么[A,B]]要么[A,Iterable [B]]
def reduce[A, B](xs: Iterable[Either[A, B]]): Either[A, Iterable[B]] =
xs.collectFirst {
case Left(x) => x
} match {
case Some(x) => Left(x)
case None => Right(xs.collect{case Right(y)=> y})
}
谁能帮助我找到一个更好的方式,如果这一块是不是?
要实现转型是有点暧昧。你的输入列表包含例如'Right [String]'的一半和各种不同'Left [Exception]'的一半。您希望将其减少为一个例外或字符串列表。如果有例外,应该采取哪种例外在输入中有十个不同点? –
你说得对。我想只考虑它会隐藏其他的第一个异常(或任何左值),但对我的用例来说是可以接受的。 –
这是http://stackoverflow.com/questions/7230999/how-to-reduce-a-seqeithera-b-to-a-eitherseqa-seqb的副本。 – ziggystar