How can an Iterable of Try values be converted into a Try of Iterable? If the Iterable contains a failure then the first Failure should be returned, if there are no failures then an Iterable of the Success values should be returned.
As an example, assume the conversion function is called squash:
import scala.util.{Try, Success, Failure}
def squash[U](iterable : Iterable[Try[U]]) : Try[Iterable[U]] = ???
The expected behavior for an Iterable containing failures:
val containsFailure : Iterable[Try[Int]] =
Iterable[Try[Int]](Success(42), Failure(new Exception("foo")), Success(43), Failure(new Exception("bar")))
assert(squash(containsFailure) == Failure(new Exception("foo")))
And the expected behavior for an Iterable with no failures:
val noFailures : Iterable[Try[Int]] =
Iterable[Try[Int]](Success(42), Success(43), Success(44))
assert(squash(noFailures) == Success(Iterable(42,43,44)))
I am looking for a solution that only contains standard scala functionality, please don't include libraries such as scalaz or cats as part of the answer.
Thank you in advance for your consideration and response.