The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null.
Important points :
- The instance of an Option that is returned here can be an instance of Some class or None class in Scala, where Some and None are the children of Option class.
- When the value of a given key is obtained then Some class is generated.
- When the value of a given key is not obtained then None class is generated.
Example :
object option
{
def main(args : Array[String])
{
val name = Map( "Nidhi" - > "author" ,
"Geeta" - > "coder" )
val x = name.get( "Nidhi" )
val y = name.get( "Rahul" )
println(x)
println(y)
}
}
|
Output:
Some(author)
None
Here, key of the value Nidhi is found so, Some is returned for it but key of the value Rahul is not found so, None is returned for it.
Different way to take optional values
- Using Pattern Matching :
Example :
object pattern
{
def main(args : Array[String])
{
val name = Map( "Nidhi" - > "author" ,
"Geeta" - > "coder" )
println(patrn(name.get( "Nidhi" )))
println(patrn(name.get( "Rahul" )))
}
def patrn(z : Option[String]) = z match
{
case Some(s) => (s)
case None => ( "key not found" )
}
}
|
Output:
author
key not found
Here, we have used Option with Pattern Matching in Scala.
- getOrElse() Method:
This method is utilized in returning either a value if it is present or a default value when its not present. Here, For Some class a value is returned and for None class a default value is returned.
Example:
object get
{
def main(args : Array[String])
{
val some : Option[Int] = Some( 15 )
val none : Option[Int] = None
val x = some.getOrElse( 0 )
val y = none.getOrElse( 17 )
println(x)
println(y)
}
}
|
Here, the default value assigned to the None is 17 so, it is returned for the None class.
- isEmpty() Method:
This method is utilized to check if the Option has a value or not.
Example:
object check
{
def main(args : Array[String])
{
val some : Option[Int] = Some( 20 )
val none : Option[Int] = None
val x = some.isEmpty
val y = none.isEmpty
println(x)
println(y)
}
}
|
Here, isEmpty returns false for Some class as it non-empty but returns true for None as its empty.