Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Scala: Option Type (Part 2)

DZone's Guide to

Scala: Option Type (Part 2)

This primer for Scala's Option Type will show you three different ways of accessing results from Options: getOrElse, foreach, and match expressions.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

In the previous article, I had given a very basic introduction to the Option Type here. We saw that one way to check if a value is present by means of an isDefined method of the option, and if it is present, get the value via the get method. However, using the get method is not an elegant way to check if the value is defined in an option because you might forget about checking with the isDefined method before, leading to an exception at runtime — which is as good as getting a NullPointerException. It is recommended to stay away from this way of accessing Options whenever possible.

There are several ways to access the result from the Option, but the three most common ways are:

  • getOrElse
  • foreach
  • Match expressions
  • Let’s look at our Employee class

    case class Employee {
        val empid: Integer ,
        val name: String="",
        val gender: Option[String]
    }


    Use the getOrElse() Method

    The following is an example program to show how to use getOrElse() methods to access a value or a default value when no value is present:

    def main(args: Array[String]) {
        val emp1: Employee = Employee(101, "Dave", Some("M"))
        val emp2: Employee = Employee(102, "Alicia", Some("F"))
        val emp3: Employee = Employee(103, "Alex", Option(null))
        val empMap = Map(101 -> emp1, 102 -> emp2, 103 -> emp3)
        val empObject1:Option[Employee] = empMap.get(103)
        val empObject2:Option[Employee] = empMap.get(104)
        println(empObject1.getOrElse("Invalid EmployeeId"))
        println(empObject2.getOrElse("Invalid EmployeeId"))
    }


    Output

    Employee(103,Alex,None)
    Invalid EmployeeId


    Use foreach

    foreach comes in handy when certain tasks/operations need to be done only if the option value is present:

    def main(args: Array[String]) {
        val emp1: Employee = Employee(101, "Dave", Some("M"))
        val emp2: Employee = Employee(102, "Alicia", Some("F"))
        val emp3: Employee = Employee(103, "Alex", Option(null))
        val empMap = Map(101 -> emp1, 102 -> emp2, 103 -> emp3)
        val empObject1: Option[Employee] = empMap.get(101)
        val empObject2:Option[Employee] = empMap.get(104)
        empObject1.foreach { x => println(x) }
        empObject2.foreach { x => println(x) }
    }


    Output

    Employee(101,Dave,Some(M))
    Nothing gets printed as 104 doesn’t exist


    Use a Match Expression

    Another good way to access is using the match expression:

    def main(args: Array[String]) {
        val emp1: Employee = Employee(101, "Dave", Some("M"))
        val emp2: Employee = Employee(102, "Alicia", Some("F"))
        val emp3: Employee = Employee(103, "Alex", Option(null))
        val empMap = Map(101 -> emp1, 102 -> emp2, 103 -> emp3)
        val empObject1: Option[Employee] = empMap.get(102)
        val empObject2: Option[Employee] = empMap.get(104)
        val empObjectList = List(empObject1, empObject2)
        empObjectList.foreach { x =>
            x match {
                case Some(emp) => println(emp.name)
                case None => println("Invalid Employee ID")
            }
        }
    }


    Output

    Alicia
    Invalid Employee ID


    In the next article, I’ll make an attempt to explain filtering an option, using options with for comprehension, and Options and flatMaps.

    Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

    Topics:
    java ,option type ,foreach ,match expression ,getorelse ,tutorial ,scala by example

    Opinions expressed by DZone contributors are their own.

    {{ parent.title || parent.header.title}}

    {{ parent.tldr }}

    {{ parent.urlSource.name }}