Basically I want to extract a bunch of Options a, b, etc. Is this the best way to do this in Scala? It looks kind of confusing to me to have the for-yield in parenthesis.
(for {
a <- a
b <- b
c <- c
...
} yield {
...
}) getOrElse {
...
}
Try using map
and flatMap
instead. Assume you have the following class hierarchy:
case class C(x: Int)
case class B(c: Option[C])
case class A(b: Option[B])
val a = Some(A(Some(B(Some(C(42))))))
In order to extract 42
you can say:
a.flatMap(_.b).flatMap(_.c).map(_.x).getOrElse(-1)
This is roughly equivalent to:
for(
a <- a
b <- a.b
c <- b.c)
yield c.x
except that it returns Some(42)
. In fact for
comprehension is actually translated into a sequence of map
/flatMap
calls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With