Sunday, December 26, 2010

Liberate Me Ex Null

Not sure if I got the Latin perfect, but please, future language designers, save us from null!
Even bright new languages like Scala can't help us from the land of null:
def foo( string: Some[String] ) = {
  string.get
}

foo( null )
java.lang.NullPointerException at Main$$anon$1.foo(test.scala:2)
"Some" (and "None") are from the "Option" type, which is a way of letting you say you have something or nothing, while still preserving type safety.  But because of null compatibility with the JVM, Some[] is nullable!  A more dynamic language, Dylan, can type check this pattern:
define method foo (string :: <string>) end;
This method takes a string - and does not accept a null value.  If you want to allow nulls (or false, in Dylan's case), you write:
define method foo (string :: false-or(<string>)) end;
which is ultimately shorthand for a type union:
define method foo (string :: type-union(<string>, singleton(#f))) end;