Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at the Option type in Scala.
Scala has a special type called “Option” to handle optional values. In programming world, sometimes a variable will have null instead of actual value and this would cause NullPointerException. To handle such situations, Scala introduced the type “Option“.
When we declare a variable as “Option” type, it can have two possible values, i.e., Some(x) where x is the actual value or None where there is no value. Calling getOrElse() method on the variable will give us the actual value stored in the Option variable.
Let’s look at the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.clearurdoubt object OptionTypeDemo { def main(args: Array[String]) { val a: Option[String] = Some("Hello") val b: Option[String] = None println(s"a=${a.getOrElse("default")} b=${b.getOrElse("default")}") val map = Map("A" -> 1, "B" -> 2, "C" -> 3) println(s"A = ${map get "A" getOrElse(-1)}") // No issues as the return value is of Option type println(s"D = ${map get "D" getOrElse(-1)}") // No issues as the return value is of Option type println() println(s"A = ${map("A")}") // no issues as key is existing println(s"D = ${map("D")}") // No Such Element Exception } } |
Output:
The get() method of Map class returns a Option type value where as map(key) will return actual value in the Map for the key. if the key is not existing in the map, it will throw NoSuchElementException. So it’s a nice approach to handle them using Option type.
Happy Learning.
Please leave a reply in case of any queries.