Hack: cannot turn a non-null into a nullable in a loop with `?->`
I'm using the ?-> operator inside a loop to get to deep-nested values in a recursive structure. However, without exiting early from the loop, Hack keeps complaining.
Using ?-> on the initial access:
<?hh // strict
class Test
{
private Map<string, Test> $testMap = Map {};
public function getNestedTestMap(array<string> $path): ?Map<string, Test>
{
$testMap = $this->testMap;
foreach ($path as $part) {
$testMap = $testMap?->get($part)?->testMap;
}
return $testMap;
}
}
test.php|12 col 24 error| You are using the ?-> operator but this object cannot be null. (Typing[4117])
test.php|6 col 13 error| This is what makes me believe it cannot be null
Or, without ?-> on the initial access:
<?hh // strict
class Test
{
private Map<string, Test> $testMap = Map {};
public function getNestedTestMap(array<string> $path): ?Map<string, Test>
{
$testMap = $this->testMap;
foreach ($path as $part) {
$testMap = $testMap->get($part)?->testMap;
}
return $testMap;
}
}
test.php|11 col 34 error| You are trying to access the member get but this object can be null. (Typing[4064])
test.php|11 col 24 error| This is what makes me believe it can be null (use of ?-> operator)
So, Hack knows that $testMap can be null inside the loop. But it also can't be null while inside the loop, because it's not nullable before the first iteration.
Thanks for the repro case. I bet this is because it's an unresolved of both; the ?-> should probably not error in this case, though I'm not sure how feasible that is to do.
I am going over old issues on this repository, to see which ones apply to the current versions of hhvm.
This does not report an error in hhvm 4.56 anymore. Hack understands that $testMap could be null if ->get() returns null at some point.
The typechecker is actually quite smart with the new inference engine.