Published December 19, 2015

NullPointerException is an obvious runtime problem in most Java applications. But it's not limited to Java, in PHP for example we could get a "Trying to get property of non-object". But today, there's a compilation alternative to this runtime problem.

Maybe Cat | Option[Cat] | Optional<Cat>

Scala is a modern functional (and Object Oriented) language based on the JVM. I did a lot of Scala during the past year, mostly with the Spark framework for distributed computing. In Java, if you try to access a element in a Map<String, Cat> for example, the signature will look like this:

/**
 * Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
 *
 * @return Cat or null
*/
public Cat get(String key);

And it's correct (for the compiler) to write:

this.get("Schroedinger").miaou();

If the Cat is here, it's fine. If he's not, the program crash with a NullPointerException. The compiler will not help you to catch this kind of bugs.

In Scala the signature for a type Map[String, Cat] is:

def get(key: String): Option[Cat]

So you cannot write something like before. The compiler will not allow it because the object Option[Cat] doesn't have a miaou method. So, how did we manage this? We use pattern matching to check the None option. Indeed, the Option[Map] type is divided into two types: Some[Cat] and None.

this.get("Schroedinger") match {
  Some(cat) => cat.miaou()
  None      => // do something
}

Scala is not a strict language so it's possible to get the content of an option or a null with the get method on Option[Cat]:

// throw a NullPointerException
this.get("Schroedinger").get.miaou()

This concept of optional type come from functional programming. The last version of Java introduces a lot of functional programming stuff, it's now possible to use the new type: Optional<Cat>.

And, last but not least, it's not a new hype feature from 2015, some great (and old) languages like Haskell has the Maybe type for a long time. Maybe Cat could be Just Cat or Nothing.


In conclusion, if you want to know more about this amazing functionality: