如何在Scala中将此map/flatMap转换为for comprehension? [英] How to convert this map/flatMap into a for comprehension in Scala?
问题描述
如何将此map/flatMap转换为,以供理解,请解释其工作方式,谢谢.
How to convert this map/flatMap into a for comprehension, and please explain how it works, thanks.
def compute2(maybeFoo: Option[Foo]): Option[Int] =
maybeFoo.flatMap { foo =>
foo.bar.flatMap { bar =>
bar.baz.map { baz =>
baz.compute
}
}
}
推荐答案
您的代码可以翻译为:
def compute2(maybeFoo: Option[Foo]): Option[Int] =
for {
foo <- maybeFoo
bar <- foo.bar
baz <- bar.baz
} yield baz.compute
Quotes from Programming in Scala, Second Edition:
通常,for表达式的形式为:
Generally, a for expression is of the form:
for ( seq ) yield expr
在这里,seq是生成器,定义和过滤器的序列,在连续的元素之间带有分号.
Here, seq is a sequence of generators, definitions, and filters, with semi-colons between successive elements.
此表达式包含一个生成器,一个定义和一个过滤器:
This for expression contains one generator, one definition, and one filter:
for {
p <- persons // a generator
n = p.name // a definition
if (n startsWith "To") // a filter
} yield n
使用一个生成器翻译表达式
首先,假设您有一个简单的表达式:
First, assume you have a simple for expression:
for (x <- expr1) yield expr2
其中x是一个变量.这样的表达式被翻译为:
where x is a variable. Such an expression is translated to:
expr1.map(x => expr2)
翻译以生成器和过滤器开头的表达式
现在,考虑将前导生成器与某些生成器结合在一起的表达式 其他元素.用于表达的形式:
Now, consider for expressions that combine a leading generator with some other elements. A for expression of the form:
for (x <- expr1 if expr2) yield expr3
被翻译为:
expr1 withFilter (x => expr2) map (x => expr3)
翻译以两个生成器开头的表达式
下一个案例处理以两个生成器开头的表达式,如:
The next case handles for expressions that start with two generators, as in:
for (x <- expr1; y <- expr2) yield expr3
上面的for表达式被翻译为flatMap的应用程序:
The for expression above is translated to an application of flatMap:
expr1.flatMap(x => for (y <- expr2) yield expr3)
这篇关于如何在Scala中将此map/flatMap转换为for comprehension?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!