如何flatMapScala集合并在结果中保留原始值?
考虑一个函数f : A -> Option[B]。
我想使用 flatMap f,但在结果中也保留原始值,作为一对 values (A,B)。
我可以这样写:
collection.flatMap(a => {
f(a) match {
case Some(b) => Some((a,b))
case None => None
}
})
但是有更好的方法吗?
回答
这也有效。
for {
a <- collection
b <- f(a)
} yield (a,b)
- Note: after desugaring for comprehension in this answer you get the code from Jatin's answer.