Skip to content

Instantly share code, notes, and snippets.

@danclien
Created August 10, 2013 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danclien/6202192 to your computer and use it in GitHub Desktop.
Save danclien/6202192 to your computer and use it in GitHub Desktop.
Playing around with for comprehensions to check for None in Option[T].
//Setup Option[String]s
val maybeValue1 : Option[String] = Some("Value1")
val maybeValue2 : Option[String] = Some("Value2")
val maybeValue3 : Option[String] = None
// Manually checking each value
val result = maybeValue1 match {
case None => None
case value1 => maybeValue2 match {
case None => None
case value2 => maybeValue3 match {
case None => None
case value3 => (value1, value2, value3)
}
}
}
// Checking each value using a for comprehension
(for { _ <- maybeValue1; _ <- maybeValue2; _ <- maybeValue3 } yield ()) match {
case None => println("Handle error here")
case _ => println("Do stuff here")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment