null object

Scala best practice: Eliminate null values from your code

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 20.5, “Scala best practice: Eliminate null values from your code.”


Tony Hoare, inventor of the null reference way back in 1965, refers to the creation of the null value as his “billion dollar mistake.” In keeping with modern best practices, you want to eliminate null values from your code.

A Scala “Null Object” example

A Null Object is an object that extends a base type with a null or neutral behavior. Here’s the Scala version of the Java example Wikipedia uses to demonstrate this:

trait Animal {
  def makeSound()

class Dog extends Animal {
  def makeSound() { println("woof") }

class NullAnimal extends Animal {
  def makeSound() {}

As you can imagine, later in your application you might have some code like this: