The flatMap method of the Success is implemented like this:
def flatMap[U](f: T => Try[U]): Try[U] =
try f(value)
catch {
case NonFatal(e) =&g
A regular flatMap takes a sequence of sequences, and put all the elements into one big "flat" sequence.
Slight correction:
A regular flatMap
takes a sequence (more generally monad) , has an argument which is a function converting an element into a sequence (monad), and returns a "flat" sequence (monad).
For comparison purposes, the gory substeps mentioned here :). The flatmap
method iterates over input sequence invoking f(element)
, but creates a singular new result sequence. The "flatten" part is applied after each function argument application, f(element)
- it does a nested iteration over the resulting sub-sequence, yielding each entry in the singular result sequence.
The equivalent for Success
, with a value
inside (more generally a monad):
flatmap
has an argument which is a function converting Success
into Try
= Success(value)
OR Failure(exception)
. After f(value)
is applied, the result is already a Try
. The "flatten" part is a trivial/null operation: iterating over this function result would give just one entry, hence Try
/Success
/Failure
don't even need to implement Iterable
). Doesn't wrap additional layers of Success
/Failure
, and so returns a "flat" Try
.
I.e. The "flat" part means it doesn't cascade Success
/Failure
wrappers, just as a sequence's flatmap
doesn't cascade sequences in a (value tree) hierarchy.
this is different to map
, whose argument is a function converting Success
into an arbitrary type U
; after f(value)
is applied, map must add an additional layer of new Success
/Failure
wrapping around the value
/exception
.