Scala: how to understand the flatMap method of Try?

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

    Without entering into monads, instead of thinking about it in terms of collections, you could think of it in terms of structures (where a collection becomes a structure with many entries).

    Now, take a look at the signature of Try.flatmap (from your post):

    def flatMap[U](f: T => Try[U]): Try[U] the function f transforms T into a Try[U] in the context of Try[T].

    In contrast, imagine the operation were 'map', the result would be:

    def badMap[U](f: T => Try[U]): Try[Try[U]]

    As you can see, flatmap is 'flattening' the result into the context of Try[T] and producing Try[U] instead of the nested Try[Try[U]].

    You can apply the same 'flattening of nested structure' concept to collections as you mention.

提交回复
热议问题