A new approach for null handling
For those who have been following the saga of making Scala 3 more null-safe, I recommend checking out this new PR, which introduces a new approach.
Reminder of the context: for Scala 3 (whether 3.0 or possibly a later release), the desire is to no longer allow
null as a valid value for arbitrary
AnyRefs. Instead, you would need to treat it explicitly — if your value might be nullable, you have to use a type of
Foo | Null. This would reduce the scope of possible null pointer exceptions even more than is traditional in Scala.
But if you have one of these values, it’s kind of a hassle to use it, because you have to deal with those possible
nulls in every dereference. That’s a nuisance when working with Java APIs, which often have legitimate reasons to return
null. You will often know from context that this value can’t possibly be
null, but the type allows it.
So the question is, how do we make it non-awful to work with this sort of API? There have been several experiments, with various levels of success. This PR introduces a new approach: a language import,
scala.language.unsafeNulls. If that is in-scope, then you can act in a Java-ish way and ignore the possible
nulls — that
| Null in the type gets ignored for purposes of the compiler checking method calls and the like. Outside of that scope, though, you have to wrestle with
Personally, I like it: this feels like the right way forward. It is relatively easy to use, but keeps the “danger zone” limited to specific code blocks. That strikes a good balance between usability and type safety.
(They also propose a compiler flag that allows you to turn this feature on globally — I would never recommend using that, but if your code does an enormous amount of Java API work I suppose it may make sense.)
Anyway, usual reminders: this is just a PR, not yet in Dotty mainline and it isn’t at all clear whether or when it would land in Scala 3. But I’m cheering for it…