3 ms·
Most of my work at Facebook was using Hack. Nullness is a key part of Hack's stype system [1] and this solves so many BS errors. That's not to say you couldn't
by cletus 2y ago
Most of my work at Facebook was using Hack. Nullness is a key part of Hack's stype system [1] and this solves so many BS errors. That's not to say you couldn't get a null where you weren't expecting one, particularly because this was a later addition to the language so the code still had a lot of legacy "mixed" types that basically mean anything (mirroring the PHP roots where you could pass basically anything).
Some questions though.
First, what about nullable arrays? There are examples of String![] where the objects can be null but what about the array itself? As a reminder this is entirely legal in Java:
String labels[] = null;
Does that mean you have to declare it:
String![]! labels;
?
In Hack, this is easy:
vec<String> $foo; // neither foo nor the elements are null
?vec<string> $foo; // the elements are non-null but foo can be null
vec<?string? $foo; // foo cannot be null, elements can be
?vec<?string> $foo; // either can be null
In practice, there's really little reason to ever use a null array so the default really should be that something isn't nullable. I understand the issue with Java is that all legacy code assumes nullability so that's an issue.
String? id(String! arg) { return arg; }
String s = null;
Object! o1 = s; // NPE
Object o2 = id(s); // NPE
Object o3 = (String!) s; // NPE
As for this example, shouldn't (2) and (3) be compiler errors?
As for the last, I really like Hack's as enforcement operators here rather than Java's casting eg:
class A {}
class extends B {}
void foo(B $b) {}
?B $b = new B();
foo($b); // compiler error
A $a = $b as A; // runtime error if $b is null
foo($a as B); // runtime error if $a is not a B
?B $b2 = $a as ?B; // $b2 is cast to B if it is one, otherwise null is returned
Anyway, the question becomes can you retrofit this to the Java SDK? What does it look like for legacy code?
[1]: https://docs.hhvm.com/hack/types/nullable-types https://docs.hhvm.com/hack/types/nullable-types
- jayd16 2y agoPresumably its just : String![]? labels = null;