Option
A function computes a return value. But sometimes nothing valid can be returned. Nothing is possible. With an Option
, we can specify None
instead of a value.
With optional data, our algorithms become clearer. We clearly specify whether "None
" or something valid is available. We indicate absence.
Option
exampleHere the getName
def
returns an Option
String
. If the argument we pass to it is at least 1, we get an Option
containing the String
"Oxford."
None
, which is an option with no value.def getName(value: Int): Option[String] = { // Return a String Option based on the argument Int. if (value >= 1) { return Option("Oxford") } else { return None } } object Program { def main(args: Array[String]): Unit = { // Accepted to Oxford. println(getName(10)) // Rejected. println(getName(0)) } }Some(Oxford) None
Option
, MapThe Map collection uses an Option
when we call its get()
method. Sometimes nothing exists at the key specified. None
is returned.
Option
, we can always call isDefined
. This returns true if the Option
does not have a None
value, and false otherwise.String
) when the get()
method is invoked.object Program { def main(args: Array[String]): Unit = { val ids = Map(("a12", "Mark"), ("b19", "Michelle")) // Get Option from our map. val result = ids.get("b19") if (result.isDefined) { println(result.get) } } }Michelle
GetOrElse
Here is another method on an Option
. We can use getOrElse
to access the inner value of the Option
, unless there is None
. If None
, we get the argument back.
None
can occur.object Program { def main(args: Array[String]): Unit = { val words = Map(1000 -> "one-thousand", 20 -> "twenty") // This returns None as the Option has no value. val result = words.get(2000) println(result) // Use getOrElse to get a value in place of none. val result2 = result.getOrElse("unknown") println(result2) } }None unknown
None
We can use the null
keyword in assignments. But for top-quality code, Option
is preferred. Generally in languages we like to copy the core types like Map, which uses Options.
List
findThe find()
method on Lists returns an Option
. It may be clearer to use find()
instead of indexOf()
as we can test the option to determine if an element was not found.
Many things in life are optional. For these things, we can use an Option
type in Scala. With an Option
, we express absence or "nothingness" with clarity.