Part1: Scala – Option Type


A powerful Scala is to use Option Type when returning a value can be null. When we write a function to get information in a database, we don’t know exactly what all data will fill out or not. We got an exception because of null value. It makes programs errors if it doesn’t handle in these cases. In scala, it is better for handle it by Option Type or Option[A]

Option[A] is a container for an option value of type A. if the value of type A is present, the Option[A] is an instance of Some(A). If type A is absent, the Option[A] is an instance of None class.

An option is mandatory if returning data include a null value.

Creating an Option Type

Usually, we can simply create an Option[A] for the present a value by using Some class:

If we know that it absent, it simply assigns None

We can directly assign a value to a variable. In a function, it runs the same.

It returns an Option[String] when it got a correct string. The same as above example, it returns None, when a string is null

Working with Scala Option

Suppose, we are building a User class to store user information with username, password, and address. username and password are required, so we don’t care that these value will be null. But address can be an empty value

To address needs to use an Option[String] type for handle a null value.

We are 2 users and user1 don’t have an address with None value. user2 has addressed,

User2: you can get information by user2.address.get.

User1: it will throw error exception because the address is None. In this case, we need to handle it. You can provide a default value by user1.getOrElse(“not specified”)

We will discuss more the way to handle Option Type in next tutorial

Pattern Matching

Some is case class, so it possible to use it in a pattern. We can get an Option[A] using Pattern Matching.

If a value is present, it matches a Some( A).
If value is absent, it match a None


Here’s example to use Map/FlatMap/For/Filter with Option Type
Map example:  

Flatmap example: 

For example:  

Filter example:   


You May Also Like

About the Author: Nguyen Dinh Thuc

Leave a Reply

Notify of