Search code examples
arraysvectornullablehhvmhacklang

Add Elements to nullable Vector


Alright, so I got a private ?Vector $lines which is empty when constructing the object and now I want to add strings to that Vector. The following Hack code works well:

<?hh
class LineList {
    private ?Vector<string> $lines;

    public function addLine(string $line): void {
        $this->file[] = trim($line);
    }
}

But when checking the code with hh_client, it gives me the following warning:

$this->file[]]: a nullable type does not allow array append (Typing[4006])
[private ?Vector<string> $lines]: You might want to check this out

Question: How do I add elements to the Vector without that the checker pushs this warning?


Solution

  • The easiest way would be to not use a nullable Vector. private Vector<string> $lines = Vector {}; gets around the need for a constructor too.

    Otherwise, you'll need to check if the value isn't null, then append to it:

    public function addLine(string $line): void {
        $vec = $this->lines;
        if ($vec !== null) $vec[] = trim($line);
    }
    

    You can't just check if $this->lines !== null as it is possible for it to change value between checking and appending (with something like a tick function), hence why it is assigned to a local variable instead.