考虑一个函数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)
但是有更好的方法吗?
这也有效。
for {
a <- collection
b <- f(a)
} yield (a,b)
Run Code Online (Sandbox Code Playgroud)