Scala – Option type

Scala has a standard type named Option for optional values. Such a value can be of two forms. It can be of the form Some(x) where x is the actual value. Or it can be the None object, which represents a missing value.

 

it is possible to store value types in hash maps, and null is not a legal element for a value type. For instance, a HashMap[Int, Int] cannot return null to signify “no element.” By contrast, Scala encourages the use of Option to indicate an optional value. This approach to optional values has several advantages over Java’s. First, it is far more obvious to readers of code that a variable whose type is Option[String] is an optional String than a variable of type String, which may sometimes be null. But most importantly, that programming.

 

object OptionType extends App{

  val m1 = Map("usa"-> "DC","India"->"delhi")
  def show(x: Option[String]) = x match {
    case Some(s) => s
    case None => "?" }
  println(show(m1.get("china")))
  println(show(m1.get("Core Universe")))
  println(show(m1.get("India")))

}