Scala Option, Some, None syntax examples

Today I’m sharing some examples of the Scala Option/Some/None syntax. These examples will show how to use an Option for the var fields in a Scala class. Then I’ll show how to set those Option fields, and then get the values from the Option fields.

To get started, we’ll need a little case class to represent an Address:

Initialize Scala variables with Option, None, and Some (not null)

Summary: How to properly use the Scala Option/Some/None idiom to initialize empty var fields -- and specifically how not to use null values for the same purpose.

When you get started in the Scala world, you quickly learn that null values are a bad thing. Scala makes it easy to replace null values with something better, and that something better is what I call the Option/Some/None pattern (or idiom).

Scala best practices: null values, Option, Some, and None

In his excellent book, Beginning Scala, David Pollak provides a series of statements that can be considered as a recipe for avoiding the use of null values in your Scala code. I've organized his statements here in the following three sections.

1) General rules about null and Option

We begin with the following general rules regarding the use of null values in Scala code:

Using the Scala Option, Some, and None idiom (instead of Java null)

A powerful Scala idiom is to use the Option class when returning a value from a function that can be null. Simply stated, instead of returning one object when a function succeeds and null when it fails, your function should instead return an instance of an Option, where the Option object is either: