Scala Option: A Gentle Introduction
Scala Option[ T ] is a compartment for nothing or one component of a given kind. An Option[T] can be either Some[T] or No object, which addresses a missing worth. For example, the get technique for Scala’s Map produces Some(value) if a value comparing to a given key has been or None if the given key isn’t mention in the Map.
Scala’s Option
type is a fundamental concept in functional programming that addresses the challenge of representing absence of a value in a type-safe manner. Option
is used to encapsulate an optional value that may or may not exist, providing a safer alternative to null
references commonly used in other languages.
The Option
type in Scala is defined as a generic container that can hold either a Some
value, representing the presence of a value, or None
, representing the absence of a value. This approach eliminates the risk of null pointer exceptions and encourages safer and more predictable code.
Use case 1:
object prwatech {
// Main method
def main(args: Array[String])
{
// Creating a Map
val name = Map("Abhi" -> "author",
"Prabha" -> "coder")
// Accessing keys of the map
val x = name.get("Abhi")
val y = name.get("Sandeep")
// Displays Some if the key is
// found else None
println(x)
println(y)
}
}
Output:
Some(author)
None
Here, key of the value Abhi so, Some is return for it but key of the value Sandeep so, None is return for it.
Use case 2:
Using Pattern Matching:
object prwatech {
// Main method
def main(args: Array[String])
{
// Creating a Map
val name = Map("Abhi" -> "author",
"Prabha" -> "coder")
//Accessing keys of the map
println(patrn(name.get("Abhi")))
println(patrn(name.get("Rahul")))
}
// Using Option with Pattern
// matching
def patrn(z: Option[String]) = z match
{
// for 'Some' class the key for
// the given value is displayed
case Some(s) => (s)
// for 'None' class the below string
// is displayed
case None => ("key not found")
}
}
Output:
author
key not found
Use case 3:
getOrElse() Method:
This technique returns either a value in the event that is available or a default value when its not available. Here, For Some class a value is return and for None class a default value returns.Scala Option: A Gentle Introduction
object prwatech {
// Main method
def main(args: Array[String])
{
// Using Some class
val some:Option[Int] = Some(5)
// Using None class
val none:Option[Int] = None
// Applying getOrElse method
val x = some.getOrElse(0)
val y = none.getOrElse(1)
// Displays the key in the
// class Some
println(x)
// Displays default value
println(y)
}
}
Output:
5
1