Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Playing with Options
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
You can’t perform that action at this time.