Open In App

Scala | Option

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 :



Example :




// Scala program for Option
  
// Creating object
object option
{
  
    // Main method
    def main(args: Array[String])
    {
  
        // Creating a Map
        val name = Map("Nidhi" -> "author"
                        "Geeta" -> "coder")
  
        // Accessing keys of the map
        val x = name.get("Nidhi")
        val y = name.get("Rahul")
  
        // Displays Some if the key is
        // found else None 
        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


Article Tags :