Scala:如何了解TryMap的flatMap方法? [英] Scala: how to understand the flatMap method of Try?

查看:217
本文介绍了Scala:如何了解TryMap的flatMap方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

成功的flatMap方法是这样实现的:

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) => Failure(e)
    }

我很明白这种方法在做什么,它有助于我们以避免编写很多代码。

I kinda understand what this method is doing, it helps us to avoid writing a lot of catching code.

但是在什么意义上它与普通的flatMap类似?

But in what sense is it similar to the regular flatMap?

一般的flatMap需要一系列的序列,并将所有元素放在一个大的平序列中。

A regular flatMap takes a sequence of sequences, and put all the elements into one big "flat" sequence.

但是Try的flatMap方法并不是真的平坦化了。

But the flatMap method of Try is not really flattening anything.

那么,如何理解Try的flatMap方法?

So, how to understand the flatMap method of Try?

推荐答案

没有进入monads,而不是在集合上考虑它,你可以从结构(在一个集合变成一个具有很多条目的结构) 。

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).

现在,看看 Try.flatmap (从你的帖子)的签名:

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

def flatMap [U](f:T => Try [U]):尝试[U] 函数 f 在Try [T]的上下文中将T转换为Try [U]。

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

相比之下,是'map',结果将是:

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

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

如您所见,平面图将结果扁平化为Try [T]的上下文并生成尝试[U] 而不是嵌套的尝试[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.

这篇关于Scala:如何了解TryMap的flatMap方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆