如何 flatMap Scala 集合并在结果中保留原始值?

Tra*_*Man 0 scala

考虑一个函数f : A -> Option[B]

我想使用 flatMap f,但在结果中也保留原始值,作为一对 values (A,B)

我可以这样写:

collection.flatMap(a => {
  f(a) match {
    case Some(b) => Some((a,b))
    case None => None
  }
})
Run Code Online (Sandbox Code Playgroud)

但是有更好的方法吗?

jwv*_*wvh 6

这也有效。

for {
  a <- collection
  b <- f(a)
} yield (a,b)
Run Code Online (Sandbox Code Playgroud)

  • 注意:在这个答案中进行脱糖理解后,您可以从 Jatin 的答案中获得代码。 (3认同)