Below is the definition of flatMap
taken from scala.util.Success.
final case class Success[+T](value: T) extends Try[T] {
def flatMap[U](f: T => Try[U]): Try[U] =
try f(value)
catch {
case NonFatal(e) => Failure(e)
}
}
Here the f
function takes a value of type T
and and does a possibly faulty operation. What I don't understand is why do we need to wrap application of f
with try-catch
. Here is the apply method of companion object of Try
:
object Try {
def apply[T](r: => T): Try[T] =
try Success(r) catch {
case NonFatal(e) => Failure(e)
}
}
As you can see, the operation takes place in a Try
application body already covered with try-catch
, and will not throw, but rather store the thrown exception safely. So it appears to me that it should be safe (since no exception will be thrown) to call whatever f
(the one passed to flatMap
) is.
My question is why flatMap
wraps application again with a try-catch
, how is this necessary?
P.S: Here is a relevant question, but does not answer mine: Scala: how to understand the flatMap method of Try?