Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is for-yield-getOrElse paradigmatic Scala or is there a better way?

Tags:

scala

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 {
  ...
}
like image 988
Garrett Hall Avatar asked Oct 04 '12 20:10

Garrett Hall


1 Answers

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.

like image 93
Tomasz Nurkiewicz Avatar answered Oct 16 '22 08:10

Tomasz Nurkiewicz