O'Reilly logo

Programming Scala by Alex Payne, Dean Wampler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using Nulls Versus Options

When we introduced Option in Option, Some, and None: Avoiding nulls, we briefly discussed how it encourages avoiding null references in your code, which Tony Hoare, who introduced the concept of null in 1965, called his “billion dollar mistake” (see [Hoare2009]).

Scala has to support null, because null is supported on both the JVM and .NET and other libraries use null. In fact, null is used by some Scala libraries.

What if null were not available? How would that change your designs? The Map API offers some useful examples. Consider these two Map methods:

trait Map[A,+B] {
  ...
  def get(key: A) : Option[B]
  def getOrElse [B2 >: B](key : A, default : => B2) : B2 = ...
  ...
}

A map may not have a value for a particular key. Both of these methods avoid returning null in that case. Concrete implementations of get in subclasses return a None if no value exists for the key. Otherwise, they return a Some wrapping the value. The method signature tells you that a value might not exist, and it forces you to handle that situation gracefully:

val stateCapitals = Map("Alabama" -> "Montgomery", ...)
...

stateCapitals.get("North Hinterlandia") match {
  case None => println ("No such state!")
  case Some(x) => println(x)
}

Similarly, getOrElse forces you to design defensively. You have to specify a default value for when a key isn’t in the map. Note that the default value can actually be an instance of a supertype relative to the map’s value type:

println(stateCapitals.getOrElse( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required