Sunday, 12 May 2019

Options in Scala


Options

Scala Option[ T ] is a container for zero or one element of a given type. An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map.
Example :
object OptionsVar {
  def main(args: Array[String]) {
      val islands = Map("France" -> "Europe", "Japan" -> "Asia")
      println("show(islands.get( \"Japan\")) : " + show(islands.get( "Japan")) )
      println("show(islands.get( \"India\")) : " + show(islands.get( "India")) )
   }
   def show(x: Option[String]) = x match {
      case Some(s) => s
      case None => "?"
   }
}
//Output
show(islands.get( "Japan")) : Asia
show(islands.get( "India")) : ?

Using getOrElse() Method
Following is the example program to show how to use getOrElse() method to access a value or a default when no value is present.
Example:
object Test {
   def main(args: Array[String]) {
      val a:Option[Int] = Some(3)
      val b:Option[Int] = None
      println("a.getOrElse(0): " + a.getOrElse(0) )
      println("b.getOrElse(10): " + b.getOrElse(9) )
   }
}
//Output
a.getOrElse(0): 3
b.getOrElse(9): 9

Using isEmpty() Method
Following is the example program to show how to use isEmpty() method to check if the option is None or not. 
Example
object Test {
   def main(args: Array[String]) {
      val a:Option[Int] = Some(1)
      val b:Option[Int] = None
      println("a.isEmpty: " + a.isEmpty )
      println("b.isEmpty: " + b.isEmpty )
   }
}
//Output
a.isEmpty: false
b.isEmpty: true

No comments:

Post a Comment

Use filter method to filter a Scala collection

Use filter method to filter a Scala collection To use filter on your collection, give it a predicate to filter the collection elements as...