Skip to content

Instantly share code, notes, and snippets.

@johntbush
Created March 24, 2017 16:59
Show Gist options
  • Save johntbush/d9786a526c71f03dceb422a4fd553e6e to your computer and use it in GitHub Desktop.
Save johntbush/d9786a526c71f03dceb422a4fd553e6e to your computer and use it in GitHub Desktop.
Scala Options 101
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