What is an option in Scala?
Overview
In Scala, a container of single or no elements for a specified type is referred to as an option.
An Option[T] can either be a None object, which denotes a missing value, or a Some[T] object that denotes that the option has some value.
For instance, if a value matching a given key has been located, the get() method of Scala’s Map returns the result of Some(value). It returns None if the key is not declared in the Map.
Refer to the following code for the implementation of a map.
Example
object Main{def main(args: Array[String]){val grades = Map("John" -> 8, "Sam" -> 6)val grade_john = grades.get("John")val grade_gaby = grades.get("Gaby")println("John's grade - " + grade_john)println("Gaby's grade - " + grade_gaby)}}
Explanation
- Line 5: We define a map with two entries.
- Line 7: We use the
get()method to retrieve the value forJohn. - Line 8: We use the
get()method to retrieve the value forGaby. - Lines 10-11: We print the retrieved values.
Now that we know the basic behavior of an option, we can use it to take the optional values in different ways.
Pattern matching
Instead of printing None, we can have a case statement that matches the option and return the proper message/values.
Example
object Main{def match_pattrn(option: Option[Int]) = option match {case Some(s) => (s)case None => ("Student Entry not found")}def main(args: Array[String]){val grades = Map("John" -> 8, "Sam" -> 6)val grade_john = grades.get("John")val grade_gaby = grades.get("Gaby")println("John's grade: " + match_pattrn(grade_john))println("Gaby's grade: " + match_pattrn(grade_gaby))}}
Explanation
- Lines 3–6: We define the
match_pattrn()method that accepts and returns the argument as it is if it’s notNone. Otherwise, it returns a string. - Line 10: We define a map with two entries.
- Line 12: We use the
get()method to retrieve the value forJohn. - Line 13: We use the
getmethod to retrieve the value forGaby. - Lines 15–16: We invoke the
match_pattrn()function with the retrieved values.
The getOrElse() method
The getOrElse() method is used to return a value if it’s present or a default value if it’s not present.
Syntax
def getOrElse[B >: A](default: => B): B
Example
object Main{def main(args: Array[String]){val grades = Map("John" -> 8, "Sam" -> 6)val grade_john = grades.get("John")val grade_gaby = grades.get("Gaby")println("John's grade: " + grade_john.getOrElse(-1))println("Gaby's grade: " + grade_gaby.getOrElse(-1))}}
Explanation
- Line 5: We define a map with two entries.
- Line 7: We use the
get()method to retrieve the values forJohn. - Line 8: We use the
get()method to get the value forGaby. - Lines 10–11: We invoke the
getOrElse()method on the retrieved values. The method returns-1if the retrieved value isNone.