Created
March 24, 2017 16:59
-
-
Save johntbush/d9786a526c71f03dceb422a4fd553e6e to your computer and use it in GitHub Desktop.
Scala Options 101
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
val optionHelloWorld = Option("Hello World") | |
val optionNil:Option[String] = None | |
Option(null) | |
if (optionHelloWorld.isDefined) optionHelloWorld.get | |
if (optionNil.isEmpty) "nothing here" | |
if (optionHelloWorld.isDefined) optionHelloWorld.get else "nothing here" | |
optionHelloWorld match { | |
case Some(x) => x | |
case None => "nothing here" | |
} | |
optionNil match { | |
case Some(x) => x | |
case None => "nothing here" | |
} | |
optionHelloWorld.getOrElse("nothing here") | |
optionNil.getOrElse("nothing here") | |
optionHelloWorld.getOrElse(null) | |
optionHelloWorld.orNull | |
optionNil.getOrElse(null) | |
optionNil.orNull | |
optionHelloWorld.map(_.toLowerCase) | |
optionNil.map(_.toLowerCase) | |
optionHelloWorld.fold("nothing here"){ x => | |
x.toLowerCase | |
} | |
optionNil.fold("nothing here")(_.toLowerCase) | |
val list = List("Hi","you","Are","AWEsome") | |
list.map(_.toLowerCase) | |
val listWithNulls = List("Hi","you",null,"Are","AWEsome",null) | |
//listWithNulls.map(_.toLowerCase) | |
listWithNulls.map(Option(_)) | |
listWithNulls.map(Option(_).getOrElse("").toLowerCase) | |
listWithNulls.map(Option(_)).flatten.map(_.toLowerCase) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment