There are several reasonable and idiomatic ways in the header that, as I know, return the first successful calculations, although I am most interested in how to deal with this case, when we want to know the specific failure, the last attempt, when all attempts fail. As a first attempt, we can use collectFirstand do something like the following:
def main(args: Array[String]) {
val xs = (1 to 5)
def check(i: Int): Try[Int] = {
println(s"checking: $i")
Try(if (i < 3) throw new RuntimeException(s"small: $i") else i)
}
val z = xs.collectFirst { i => check(i) match { case s @ Success(x) => s } }
println(s"final val: $z")
}
This seems like a reasonable solution if we don't care about failures (in fact, since we always return success, we never return Failure, but only Noneif there is no successful calculation).
, , , , :
def main2(args: Array[String]) {
val xs = (1 to 5)
def check(i: Int): Try[Int] = {
println(s"checking: $i")
Try(if (i < 3) throw new RuntimeException(s"small: $i") else i)
}
val empty: Try[Int] = Failure(new RuntimeException("empty"))
val z = xs.foldLeft(empty)((e, i) => e.recoverWith { case _ => check(i) })
println(s"final val: $z")
}
, "" Throwable, , , , , , , -ops.
main2, ?