Scala with Explicit Nulls!
Today in Dotty News — an extremely interesting PR has just been submitted, implementing a long-desired feature for Dotty: explicit nulls.
What’s this about? One of Scala’s inheritances from Java (via the JVM) was “the billion dollar mistake”: the existence of null
. It’s a concept that many of us are so used to that it seems totally unexceptional, but from a strong-types point of view it’s disastrous. The notion that every reference of type T could be a T or null
leads to chaos — specifically, the chaos that almost every line could, in principle, return a NullPointerException
or NPE.
Pretty much from the beginning, Scala has discouraged the use of nulls, strongly favoring Option
instead. If you implement this rigorously, never using null
in your code and wrapping everything from Java in Option
, then your odds of an NPE go way down. (Not entirely away: due to a hole in Scala’s initialization design, it’s still possible to get nulls by accident, but it doesn’t happen often.) But this is just a convention, with no real formal weight in the compiler: it’s still possible for any reference to be null
, which is annoying, and you have no way to reliably tell the compiler whether or not a reference might be null
.
This PR changes that, saying that references can’t be null
unless you explicitly mark them as such. (Modulo the initialization problem, which is left for later work.) If your FooType
value might have null
in it, you have to mark the type as FooType | Null
. We tame the null references by making them explicit, so that the compiler can keep track of when you need to manage them.
(This capability is, by the way, one of the side-effects of having union types, and one of the reasons why many of us have been cheerleading for that feature for so long.)
The PR includes wonderfully detailed documentation, which is well worth reading — check it out. It goes into far more detail about exactly how all of this would work.
As always, keep in mind that this is Very Very Early: just a PR, not yet merged to master, much less pushed through the process to become a formal Scala 3 proposal. But it’s one I’m really hoping makes it through: it cleans up a long-standing hole in Scala, and helps keep the language up to date with best practices…