How to convert this map/flatMap into a for comprehension in Scala?
问题 How to convert this map/flatMap into a for comprehension, and please explain how it works, thanks. def compute2(maybeFoo: Option[Foo]): Option[Int] = maybeFoo.flatMap { foo => foo.bar.flatMap { bar => bar.baz.map { baz => baz.compute } } } 回答1: Your code can be translated into this: def compute2(maybeFoo: Option[Foo]): Option[Int] = for { foo <- maybeFoo bar <- foo.bar baz <- bar.baz } yield baz.compute Quotes from Programming in Scala, Second Edition: Generally, a for expression is of the