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.
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)}}
get()
method to retrieve the value for John
.get()
method to retrieve the value for Gaby
.Now that we know the basic behavior of an option, we can use it to take the optional values in different ways.
Instead of printing None
, we can have a case statement that matches the option and return the proper message/values.
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))}}
match_pattrn()
method that accepts and returns the argument as it is if it’s not None
. Otherwise, it returns a string.get()
method to retrieve the value for John
.get
method to retrieve the value for Gaby
.match_pattrn()
function with the retrieved values.getOrElse()
methodThe getOrElse()
method is used to return a value if it’s present or a default value if it’s not present.
def getOrElse[B >: A](default: => B): B
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))}}
get()
method to retrieve the values for John
.get()
method to get the value for Gaby
.getOrElse()
method on the retrieved values. The method returns -1
if the retrieved value is None
.