What is an idiomatic Scala way to do batch processing with exceptions

276 views Asked by At

If I have an List[Try[Int]] that represents some results from a function.

scala> import scala.util._
scala> val result = List[Try[Int]](
      Success(1),
      Failure(new RuntimeException("first exception")),
      Success(2),
      Failure(new RuntimeException("second exception")))

If I just collect the success I'm hiding the exceptions

scala> result.collect{case Success(x)=>x}
res1: List[Int] = List(1, 2)

I could partition but the results need to be processed further

scala> val res2 = result.partition(_.isSuccess)
res2: (List[scala.util.Try[Int]], List[scala.util.Try[Int]]) = (List(Success(1), Success(2)),List(Failure(java.lang.RuntimeException: first exception), Failure(java.lang.RuntimeException: second exception)))

scala> res2._1.collect{case Success(x)=>x}
res6: List[Int] = List(1, 2)

scala> res2._2.collect{case Failure(x)=>x}
res7: List[Throwable] = List(java.lang.RuntimeException: first exception, java.lang.RuntimeException: second exception)

And this gets even more complicated if I have a List[Try[Option[Int]]].

1

There are 1 answers

2
Jet On

How if you convert the List[Try[Int]] to Try[List[Int]] ?

import scala.util.Try

val demo = List(Try(1),Try(2))

Try(demo.map(x => x.get))

It will not be complicated for List[Try[Option[Int]]] as well.

Hope i was helpful.