[英]What is the idiomatic way to do a long series of flatMaps in Scala?
I know that a for yield is converted to a series of flatMaps followed by a final map. 我知道将for yield转换为一系列flatMap,再转换为最终地图。 I find myself frequently wanting it to end instead in a final flatMap.
我发现自己经常希望它在最终的flatMap中结束。 My workaround so far has been to do a for yield followed by a flatten like the following:
到目前为止,我的解决方法是先进行for yield,然后进行如下所示的展平:
val aOpt = Some("a")
val bOpt = Some("b")
def fakeComplexFunc(s1: String, s2: String): Option[String] = Some(s1 + s2)
(for {
a <- aOpt
b <- bOpt
} yield {
// Pretend this is a long block with lots of stuff in it
fakeComplexFunc(a, b)
}).flatten
Is there a better way to do this? 有一个更好的方法吗? Is there any sort of best practice for cases like this?
对于这种情况,是否有某种最佳实践? Have I done something drastically wrong if I end up in this situation?
如果我遇到这种情况,我做错了什么吗?
You could bind the result of fakeComplexFunc
and yield it: 您可以绑定
fakeComplexFunc
的结果并产生它:
for {
a <- aOpt
b <- bOpt
c <- fakeComplexFunc(a, b)
} yield c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.