Home »
Scala
Scala Options
By IncludeHelp Last updated : October 07, 2024
Option Type
The option is a container that contains one single value which can be one of the two distinct values.
One of the two values is 'none' and others can be any object valid in the program.
The option can be used when accepting values return from a function that can return null the time of period and some value otherwise. the options class returns two Instances:
- An instance of a null class, when the function fails.
- An instance of some class, when the function and successfully.
Both these classes inherit from the option class.
Syntax
Declaration of a function that uses option as a return type:
def function_name(arguments) : Option[data_type]
Scala example to show working of option
object Demo {
def details(x: Option[String]) = x match {
case Some(s) => s
case None => "?"
}
def main(args: Array[String]) {
val student = Map("name" -> "Ram", "standard" -> "10")
println("show(student.get( \"name\")) : " + details(student.get( "name")) )
println("show(student.get( \"percentage\")) : " + details(student.get( "percentage")) )
}
}
Output
show(student.get( "name")) : Ram
show(student.get( "percentage")) : ?
Option vs. NULL: Which is better?
The option is compared to NULL in Java programming. Using null in java, for an occasional outcome need it to be handled. If not handled it may give a NullPointerException. While using the Option in scala this exception does not occur that's why its usage is a bit more effective.
Scala Option Class Methods
Some common methods of Scala Option class are:
Method |
Description |
def get : A |
Returns the value of the option. |
def isempty : Boolean |
Returns true for none value and false otherwise. |
def getOrElse(val) |
Returns value for some value in option and return the passed value if none. |
def foreach() |
Evaluates a function if a value exists otherwise nothing is to be done |
def flatmap() |
Returns the value of function for some value of option. If the value does not exists then returns None. |
def productElementName(n) |
Return the element at the n place in 0 based-index. |