Scala – options

  • date 22nd May, 2021 |
  • by Prwatech |
  • 0 Comments

Scala Option[ T ] is a compartment for nothing or one component of a given kind. An Option[T] can be either Some[T] or No object, which addresses a missing worth. For example, the get technique for Scala’s Map produces Some(value) if a value comparing to a given key has been found, or None if the given key isn’t mention in the Map.

Use case 1:

object prwatech {
   // Main method
    def main(args: Array[String])
    {
  
        // Creating a Map
        val name = Map("Abhi" -> "author", 
                        "Prabha" -> "coder")
  
        // Accessing keys of the map
        val x = name.get("Abhi")
        val y = name.get("Sandeep")
  
        // Displays Some if the key is
        // found else None 
        println(x)
        println(y)
    }
}	

Output:

Some(author)
None

Here, key of the value Abhi is found so, Some is returned for it but key of the value Sandeep is not found so, None is returned for it.

Use case 2:

Using Pattern Matching:
object prwatech {
   // Main method
    def main(args: Array[String])
    {
  
        // Creating a Map
        val name = Map("Abhi" -> "author", 
                        "Prabha" -> "coder")
  
        //Accessing keys of the map
        println(patrn(name.get("Abhi")))
        println(patrn(name.get("Rahul")))
    }
  
    // Using Option with Pattern 
    // matching
    def patrn(z: Option[String]) = z match 
    {
  
        // for 'Some' class the key for
        // the given value is displayed
        case Some(s) => (s)
  
        // for 'None' class the below string 
        // is displayed
        case None => ("key not found")
    }
}

Output:

author
key not found

Use case 3:

getOrElse() Method:

This technique returns either a value in the event that is available or a default value when its not available. Here, For Some class a value is returned and for None class a default value returns.

object prwatech {
   // Main method
    def main(args: Array[String])
    {
  
        // Using Some class
        val some:Option[Int] = Some(5)
  
        // Using None class
        val none:Option[Int] = None 
  
        // Applying getOrElse method
        val x = some.getOrElse(0)
        val y = none.getOrElse(1)
  
        // Displays the key in the 
        // class Some
        println(x)
  
        // Displays default value 
        println(y)
    }
}

Output:

5
1

Quick Support

image image