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).

Totally avoiding null values, here's the correct Scala, idiomatic way of initializing, setting, and then accessing a variable:

// 1) initialize with Option and None
var firstName = None: Option[String]

// 2) set the value with Some
firstName = Some("Al")

// 3) access the value, typically with getOrElse
println(firstName.getOrElse("No name given"))

This is shown in the Scala REPL:

scala> var firstName = None: Option[String]
firstName: Option[String] = None

scala> firstName = Some("Al")
firstName: Option[String] = Some(Al)

scala> println(firstName)

scala> println(firstName.getOrElse("No name given"))

Of course an assumption in this code is that the field firstName has no initial value.

Note that the Java approach would be to set firstName as either a null value, or in the case of a String, perhaps an empty string (""). In Scala we avoid both of those approaches and use the Option/Some/None pattern, as shown.

Note: If you simply think of null as being evil and never allow a null value in your code, the Option/Some/None pattern will quickly become your good friend.