1

好的,所以我得到了一个私有的 ?Vector $lines,它在构造对象时是空的,现在我想向该向量添加字符串。以下Hack代码运行良好:

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

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

但是当使用 hh_client 检查代码时,它给了我以下警告:

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

问题:如何在检查器不推送此警告的情况下向 Vector 添加元素?

4

1 回答 1

3

最简单的方法是不使用可为空的 Vector。private Vector<string> $lines = Vector {};也解决了对构造函数的需求。

否则,您需要检查该值是否不为空,然后附加到它:

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

您不能只检查$this->lines !== null它是否可以在检查和附加之间更改值(使用诸如刻度函数之类的东西),因此为什么将其分配给局部变量。

于 2015-01-01T00:41:56.633 回答