Created
September 16, 2014 13:35
-
-
Save vhazrati/2059aefe2ecb06a058f2 to your computer and use it in GitHub Desktop.
Playing with Options
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
object OptionPlay { | |
println("Welcome to the Scala worksheet") | |
def someCrappyJavaService = null | |
val result: Option[String] = Some("Hello") | |
def someProcessingLogic(x: String) = println(s"I would execute when there is some value like $x") | |
def opSomeProcessingLogic(x: String): Option[String] = { println(s"I would execute when there is some value like $x"); Some("Some String") } | |
//Standard Way | |
if (result != None) someProcessingLogic(result.get) | |
if (result.isDefined) someProcessingLogic(result.get) | |
for (res <- result) someProcessingLogic(res) | |
result match { | |
case None => None | |
case Some(x) => someProcessingLogic(x) | |
} | |
// Better Way! | |
result map { x => someProcessingLogic(x) } | |
result foreach { x => someProcessingLogic(x) } | |
result.toList | |
None.isEmpty | |
result.flatMap(opSomeProcessingLogic(_)) | |
result filter (_.size > 3) foreach (x => println(x)) | |
val noneResult: Option[String] = None | |
noneResult filter (_.size > 3) foreach (x => println(x)) | |
None orElse Some(10) orElse None orElse Some(1) | |
val option1 = Some(10) | |
val option2 = Some(99) | |
val option3 = Some("Hi") | |
for { | |
a <- option1 | |
b <- option2 | |
c <- option3 | |
} yield a + b + c | |
val a: Option[Int] = Some(1) | |
val b = a map (_ + 1) | |
val c = a.get + 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment