Skip to content

Instantly share code, notes, and snippets.

@vhazrati
Created September 16, 2014 13:35
Show Gist options
  • Save vhazrati/2059aefe2ecb06a058f2 to your computer and use it in GitHub Desktop.
Save vhazrati/2059aefe2ecb06a058f2 to your computer and use it in GitHub Desktop.

Revisions

  1. Vikas Hazrati created this gist Sep 16, 2014.
    48 changes: 48 additions & 0 deletions AdvancedOptions
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    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

    }