HomeSearch

Scala Option: None, get and getOrElse

Return optional values from a function with the Option class. Use None, isDefined, get and getOrElse.
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)) Output 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) } Output 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.

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) Output 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: nullMap
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.List
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-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls