4 ms·
How I wish nullable types worked in C-like languages: You cannot dereference a nullable value normally. However, inside a (x != null) block, or rather anywhere
by TheLoneWolfling 12y ago
How I wish nullable types worked in C-like languages:
You cannot dereference a nullable value normally. However, inside a (x != null) block, or rather anywhere the compiler can infer that the value cannot be null, it automagicially turns into a non-nullable type. And there's the null-safe dereference operator (.? or similar) that returns null in case the first value is null.
Similarly with casting - if you have an if block with an instanceof check, within that block the variable has the type given by the check.
You still have to have a runtime-checked NPE in some cases (in case of hotswapping, casting to non-nullable types (which should be allowed but throws a checked excption), etc), but mostly this avoids the issues with NPEs, I think.
I agree that pattern matching can be powerful, and underutilized in most language designs.
Alternatively, I've been growing more in favor of the idea of not having null at all in the base language - if you actually need it it's relatively easy to implement if you have boolean algebra on types (Nullable<x> being equivalent to Either<x, Null>, where Null is an enumerated type with one value, null. Like what you said). And that way it's explicit, and people are more likely to use a better (read: more informative) exception type). Null ends up being an exception with no additional information, which can work in some cases, but often you want additional information. Even just "NotInitialized" or something like that is often better.