Developer Blog

Using Option in Scala

| Comments

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

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

val authorName:String = if ( else "name is empty"

A best way to check for a simple Option is GetOrElse

val authorName:String ="name is empty")