Scala Option: None, get and getOrElseReturn optional values from a function with the Option class. Use None, isDefined, get and getOrElse.
dot net perls

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.

Return Option example. Here 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."

However If the value is 0 or less, we get None, which is an option with no value.

Scala program that returns Option String
def getName(value: Int): Option[String] = { // Return a String Option based on the argument Int. if (value >= 1) { return Option("Oxford") } else { return None } } // Accepted to Oxford. println(getName(10)) // Rejected. println(getName(0))
Some(Oxford) None

Option, Map. The Map collection uses an Option when we call its get() method. Sometimes nothing exists at the key specified. None is returned.

IsDefined With an Option, we can always call isDefined. This returns true if the Option does not have a None value, and false otherwise.

Get An option will return its inner value (in this case, a String) when the get() method is invoked.

Scala program that uses Option with Map
val ids = Map(("a12", "Mark"), ("b19", "Michelle")) // Get Option from our map. val result = ids.get("b19") if (result.isDefined) { print(result.get) }

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.

So We provide a default value. This helps us handle cases where None can occur.

Scala program that uses Option, getOrElse
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

Null, 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.

Exceptions: null


List find. The 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.

© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.