4.7 TheOptionType
TheOptionclass in the standard library expresses values that might or might not be present. The subclassSomewraps a value. The objectNoneindicates that there is no value.
var friend: Option[String] = Some("Fred")friend = None //No friend
This is less ambiguous than using an empty string and safer than usingnullfor a missing value.
Optionis a generic type. For example,Some("Fred")is anOption[String].
Thegetmethod of theMapclass returns anOption. If there is no value for a given key,getreturnsNone. Otherwise, it wraps the value insideSome.
val scores = Map("Alice" -> 10, "Bob" -> 7, "Cindy" -> 8) val alicesScore = scores.get("Alice") // Some(10) val dansScore = scores.get("Dan") // None
To find out what is inside anOptioninstance, you can use theisEmptyandgetmethods:
if alicesScore.isEmpty then println("No score") else println(alicesScore.get)
That’s tedious, though. It is better to use thegetOrElsemethod:
println(alicesScore.getOrElse("No score"))
IfalicesScoreisNone, thengetOrElsereturns"No score".
A more powerful way of working with options is to consider them as collections that have zero or one element. You can visit the element with aforloop:
for score <- alicesScore do println(score)
IfalicesScoreisNone, nothing happens. If it is aSome, then the loop executes once, withscorebound to the contents of the option.
You can also use methods such asmap,filter, orforeach. For example,
val biggerScore = alicesScore.map(_ + 1) //Some(score + 1) or Noneval acceptableScore = alicesScore.filter(_ > 5) //Some(score) if score > 5 or NonealicesScore.foreach(println) //Prints the score if it exists