Created
August 10, 2013 21:22
-
-
Save danclien/6202192 to your computer and use it in GitHub Desktop.
Playing around with for comprehensions to check for None in Option[T].
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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