Developer Blog

Using Option in Scala

There are many way to use Option in Scala. Per scala docs, the idiomatic way to use Option is to treat it as a collection that can have either a length of one of zero.

Let’s says we have a basic class, Author

Simple Option checking

1
2
case class Author(name:Option[String])
val author:Author = ...

The traditional way is to check if the name is defined. This way can be prone to error is you forget to add the “get” method

1
val authorName:String = if (author.name.isDefined) author.name.get else "name is empty"

A best way to check for a simple Option is GetOrElse

1
val authorName:String = author.name.getOrElse("name is empty")