Some Options
are Nones
, and get
deals with them by throwing an exception:
None.get
// java.util.NoSuchElementException: None.get
// at scala.None$.get(Option.scala:366)
// at repl.Session$App$$anonfun$1.apply(option_get.md:9)
// at repl.Session$App$$anonfun$1.apply(option_get.md:9)
If you have a default value to provide for the None
case, use getOrElse
:
None.getOrElse(-1)
// res0: Int = -1
Another practical approach is to use fold
, which lets you provide a handler for each case:
(None: Option[String]).fold("Found None")(i => s"Found an int: '$i'")
// res1: String = "Found None"
Linter | Rule |
---|---|
Scapegoat |
|
WartRemover |