C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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
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