简体   繁体   English

在Scala中进行一系列flatMap的惯用方式是什么?

[英]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.

相关问题 什么是Scala惯用的Scala处理异常的方式 - What is an idiomatic Scala way to do batch processing with exceptions 在Scala中执行map / getOrElse返回单位的惯用方式是什么? - What's the idiomatic way to do a map/getOrElse returning Unit in Scala? Scala中的地图和平面图 - Maps and Flatmaps in Scala Scala中的多个flatMaps - Multiple flatMaps in Scala 什么是从不可变列表中“删除”一个元素的惯用Scala方法? - What is an idiomatic Scala way to “remove” one element from an immutable List? 在Scala中将多个函数定义为相同类型的惯用方式是什么? - What's the idiomatic way to define multiple functions as the same type in Scala? Scala 按分隔符拆分列表的惯用方法是什么? - What's Scala's idiomatic way to split a List by separator? 如果给定的字符串包含给定的子字符串,那么惯用的 Scala 查找方法是什么? - What is the idiomatic scala way of finding, if a given string contains a given substring? 在 Scala 中,在功能上遍历和更新数据结构的惯用方法是什么? - What's an idiomatic way to traverse and update data structures functionally in Scala? 在Scala中表达单个元素的可迭代性的最惯用的方法是什么? - What's the most idiomatic way to express an iterable of a single element in Scala?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM