将元素添加到可空矢量

时间:2014-12-31 13:45:29

标签: arrays vector nullable hhvm hacklang

好吧,所以我得到了一个私有的?Vector $ lines在构造对象时是空的,现在我想向该Vector添加字符串。以下 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中添加元素?

1 个答案:

答案 0 :(得分: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是否有可能在检查和追加之间改变值(类似于tick function),因此它被分配给局部变量的原因

相关问题