by ajnin · 2y ago · 0 comments
String? id(String! arg) { return arg; }
String s = null;
Object! o1 = s; // NPE
Object o2 = id(s); // NPE
Object o3 = (String!) s; // NPE
Surely at least the two first cases should yield a compiler error. The last case you're explicit so it's borderline but I'd rather see something like : String s = ...
if (s != null) {
# Here the compiler knows that the effective type is String!
String! ss = s; # OK
}
Like this no possibility of error.In fact, I'd even prefer Objects.requireNonNull(s) be used instead since that's even more explicit than the cast in the last case. However, I'd also like for there to be an Objects.unsafeForceNonNull(s) that just bypasses any explicit check unless there's some sort of optimization that would otherwise prevent. The unsafe method lets you implement your own requireNonNull without adding a bunch of complicated static analysis.
Unfortunately this will only be checked at the runtime.
Worse, permitting this conversion at compile time means developers will ignore the warning, so we'll have actual codebases which include these conversions. Any later change to enforce nullability checking at compile time will then have a significant backwards compatibility cost.
For example they explicitly saying that standard library will not migrate to null types, at least for now.
Java currently doesn't provide any decent (general) solution for the problem of nullability - JSR-305 is a failed spec, Optional is very verbose, doesn't work for many use cases (e.g. isn't Serializable) and funnily enough there's no guarantee the Optional instance is non-null, value types (primitive and the preview support for complex ones) obviously covers only very specific use cases.