0

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]]].

raisercostin
  • 8,777
  • 5
  • 67
  • 76

1 Answers1

0

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.

Jet
  • 3,018
  • 4
  • 33
  • 48
  • This would return the first Failure found in the list. In this case the other ones are hidden and the Success(Int) results are also ignored. – raisercostin Jun 11 '15 at 11:31
  • Then you can just filter out the Option values like res6.filter(_.isDefined) for res6: List[Int] = List(1, 2) and it is not complex as well. – Jet Jun 11 '15 at 12:18