Scala: how to understand the flatMap method of Try?

后端 未结 6 2476
情深已故
情深已故 2021-02-20 05:29

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         


        
6条回答
  •  野性不改
    2021-02-20 06:26

    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.

提交回复
热议问题