You can do something similar with the usual Scala, although this is slightly larger than the Scalaz Validation .
def checkMultiple[A,B](data: Seq[A])(f: A => B): Either[Map[A,Throwable], Map[A,B]] = { val caught = data.map(a => a -> Try(f(a))) val wrong = caught.collect{ case (a, Failure(t)) => a -> t } if (!wrong.isEmpty) Left(wrong.toMap) else Right(caught.map(x => x._1 -> x._2.get).toMap) }
Here it works:
scala> checkMultiple(Seq(1,2,3,4))(x => if (x>4) throw new Exception else x) res1: scala.util.Either[Map[Int,Throwable],Map[Int,Int]] = Right(Map(1 -> 1, 2 -> 2, 3 -> 3, 4 -> 4)) scala> checkMultiple(Seq(3,4,5,6))(x => if (x>4) throw new Exception else x) res2: scala.util.Either[Map[Int,Throwable],Map[Int,Int]] = Left(Map(5 -> java.lang.Exception, 6 -> java.lang.Exception))
source share