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

Scala: The Option Type (Part 1)

DZone's Guide to

Scala: The Option Type (Part 1)

Just like Java's attempt to hide NPEs with Optionals, check out Scala's solution: the Option type. This introduction is great for Java devs looking to get into Scala.

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

Developers familiar with Java would have experienced NullPointerExceptions at some point. It is mainly used to indicate that no value or null is assigned to a reference variable or an Object.

Different languages treat null in different ways. Scala tries to solve the problem of nulls by getting rid of null values altogether and by providing a type to represent an optional/unknown value, i.e. Option[Employee].

In this case, Option is a holder for an optional value of type Employee. If the value of type Employee is present, the Option[Employee] is an instance of Some[Employee], representing a value of type Employee. If the value is absent, the Option[Employee] is the object None.

The advantage of having an Option type is that developers are forced to deal with nulls during compile time, rather than dealing with nulls during runtime.

Create an Option

The variable age may or may not have a value, as in the example below:

val age:Option[Integer] = Some(28)

OR

val age:Option[Integer] = None

OR

val age:Option[Integer] = Option(null)


Examples of an Option

Let’s create an Employee class with an Option and explore some examples of how to deal with Option:

case class Employee {
    val empid: Integer ;
    val name: String;
    val gender: Option[String];
}


Using the get() Method of a Map

The example below passes a valid key and an invalid key to fetch the elements of the map:

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)

    println(empMap.get(101))
    println(empMap.get(104))
}


Output:

Some(Employee(101,Dave,Some(M)))

None


As we can see from the above output, the return type of the get() method of Map is of type Option.

Retrieve a Value From an Option

In the example below, the program is trying to print the employee details for a given employee ID:

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 empObject = empMap.get(104)

    // println(empObject.name) <- Compilation Error
    // println(empObject.get.name) <- Runtime Error

    if (empObject.isDefined) {
        println(empObject.get.name)
    } else {
        println("Invalid Employee ID")
    }
}


Output:

Invalid Employee ID


A shorter way to achieve the same output is in the example below:

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 empObject = empMap.get(104)

    println(empObject.getOrElse("Invalid EmployeeId"))
}


Output:

Invalid Employee ID


Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:
java ,scala ,option ,nullpointerexception ,tutorial

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}