Scala Option

One good way to think about the Option is that it represents a container, more specifically a container that has either zero or one item inside:

Some is a container with one item in it
None is a container, but it has nothing in it

Option[A] is a container for an optional value of type A. If the value of type A is present, the Option[A] is an instance of Some[A], containing the value of type A. If the value is absent, the Option[A] is the object None.

We can create an Option in the below ways:

val a: Option[String] = Some(“test”)
or
val a: Option[String] = Option(“test”)

val b: Option[String] = None
or
val a: Option[String] = Option(null)

Fetching the value from Option

We can use the isDefined or isEmpty methods of Option to check if the value is present.

We can retrieve the value from the Option using the get method. The get call on a None throws NoSuchElementException(“None.get”). So always check if the value is present using isDefined or !isEmpty, before trying to fetch the value using get.

def optionCheck(option: Option[Int]): String = {
if(option.isDefined){
“It has value:”+option.get
}else{
“Nothing here!”
}
}

Providing a default value

Very often, you want to work with a fallback or default value in case an optional value is absent. This use case is covered pretty well by the getOrElse method defined on Option.

def getValue(option: Option[Int]): Int = {
option.getOrElse(0)
}

Pattern matching

Some is a case class, so it is perfectly possible to use it in a pattern, be it in a regular pattern matching expression or in some other place where patterns are allowed.

def optionString(option: Option[Int]): String = {
option match {
case Some(5) => “Five”;
case None => “None”
case _ => “Did not Match”
}
}

Scala Code

package com.scala.test

object TestOption {

def optionCheck(option: Option[Int]): String = {
if(option.isDefined){
“It has value:”+option.get
}else{
“Nothing here!”
}
}

def optionString(option: Option[Int]): String = {
option match {
case Some(5) => “Five”;
case None => “None”
case _ => “Did not Match”
}
}

def getValue(option: Option[Int]): Int = {
option.getOrElse(0)
}

def main(args: Array[String]) {
val a: Option[Int] = Some(5)
val b: Option[Int] = None
val nums: List[Option[Int]] = List(a, b)
nums.foreach {
x => {
println(“————————-“)
println(optionCheck(x))
println(optionString(x))
println(getValue(x))
println(“————————-“)
}
}
}

}

Output
————————-
It has value:5
Five
5
————————-
————————-
Nothing here!
None
0
————————-

Leave a Reply

Your email address will not be published. Required fields are marked *