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:

val a = getAnAnimal()   // some sort of Animal factory here

In this case, if the Animal that was returned is a Dog, the string woof would be printed, but if the Animal was a NullAnimal, nothing would happen. But that’s a good thing: Because getAnAnimal didn’t return a null value, a NullPointerException wasn’t thrown. A Null Object lets your program go on along its merry way.

Option, Some, and None

“Hey”, you might say, “this seems like the Scala Option, Some, and None approach.”

“Fascinating”, I reply, doing my best Spock impersonation.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.