Scala: how to understand the flatMap method of Try?

后端 未结 6 2521
情深已故
情深已故 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:08

    As you can read in A Tour of Scala: Sequence Comprehensions: "In scala every datatype that supports the operations filter, map, and flatMap (with the proper types) can be used in sequence comprehensions." In fact this means you can threat it like a monad.
    And flatMap for monad have signature like this:

    def flatMap(f: A => M[B]): M[B]
    

    All collections in scala have monadic interfaces, so you can look at monadic operations in that narrow scope as operations on sequences. But that is not the whole story. In case of some monads looking on them as on collections is more confusing than helpful. Generally flatMap applies a transformation of the monad "content" by composing this monad with an operation resulting in another monad instance of the same type. So you can look at monads in at least two ways:

    • Monad is some kind of collection (or box holding something) and elements of that collection are "content".
    • Monad is some kind of context and elements of monad are just some computations made in that context.

    Sometimes it's easier to think about monad as collection, sometimes it's easier to think about it as context. At least for me. In fact that both approaches are interchangeable, i.e. you can look at lists (collections) as nondeterministic computations which may return an arbitrary number of results.

    So in case of Try it could be easier to think about it as execution context, with two states, Success and Failure. If you want to compose few Tries then and one of them is in Failure state then whole context becomes Failure (chain is broken). Otherwise you can do some operations on the "content" of that Tries and the context is Success.

提交回复
热议问题