Scala's Option type is a big improvement in type safety over Java's null checking and NullPointerException's. Unfortunately when wrapping a value in Some there is a quite big overhead: creation of one additional object containing a reference to the value. It would be more efficient if we could represent Some as the unboxed pointer value and encode None as the null value, but at the same time preserving the type safety as we get with the Option type (for example Kotlin uses this approach in it's builtin support for nullable types). Well, we can do exactly this with value classes introduced in Scala 2.10:
final case class Option[+T](value: T = null.asInstanceOf[T]) extends AnyVal with Product with Serializable { def isEmpty: Boolean = value == null ... }
The code is on GitHub if someone wants to try it out. It's pretty much a dropin replacement for the standard Scala Option type, except when pattern matching on None where one has to use None() instead.
Memory Usage Comparisons
Below is a comparison in memory usage between the Scala Option type and the unboxed AnyValOption when allocating 1M objects each containing one optional value: