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
}
}
}
Your code can be translated into this:
Quotes from Programming in Scala, Second Edition:
Generally, a for expression is of the form:
Here, seq is a sequence of generators, definitions, and filters, with semi-colons between successive elements.
This for expression contains one generator, one definition, and one filter:
Translating for expressions with one generator
First, assume you have a simple for expression:
where x is a variable. Such an expression is translated to:
Translating for expressions starting with a generator and a filter
Now, consider for expressions that combine a leading generator with some other elements. A for expression of the form:
is translated to:
Translating for expressions starting with two generators
The next case handles for expressions that start with two generators, as in:
The for expression above is translated to an application of flatMap: