Scala Options for Dummies, part 3

You can watch the video version of this post or read the text version below. But you shouldn’t need to do both! Pick whichever one you prefer!

In part 2 of the series, we learned some ways of pattern matching an Option to figure out if it contained a Some, to get the value from a Some, or to get a safe default value from a None. As you may have guessed, this was the manual way of doing things. The Option class actually has methods to do most of this already! This is a nice lesson in the series because the below code is self-explanatory!

//
// Avoid pattern matching...common tasks are built in already!
//

val hello = " Hello World "
val nil = null

val optionNil = Option(nil) //res0: Option[Null] = None
val optionHi = Option(hello) //res1: Option[String] = Some(Hello)

// EXISTENCE

// Not this...
optionNil match {
  case Some(s) => true
  case None => false
}

//But this...
optionNil.isDefined


// VALUE
// Not this...
optionNil match {
  case Some(s) => s
  case _ => throw new NoSuchElementException("None.get")
}

optionHi match {
  case Some(s) => s
  case _ => throw new NoSuchElementException("None.get")
}

//But this...
optionNil.get
optionHi.get

// DEFAULT VALUE
// Not this...
optionNil match {
  case Some(s) => s
  case None => "None"
}

// But this...
optionNil.getOrElse("None")

// Works with values
optionHi.getOrElse("None")

// You could use this... yuk!
scala> optionNil.orNull
res11: Null = null

Leave a Reply

Your email address will not be published. Required fields are marked *