0

我有一个可能返回 Map 或 Vector 的方法,并且由于这两种类型都实现了KeyedIterable——Vector<T>特别是实现了——我想我可以用一个返回类型KeyedIterable<int, T>来覆盖这两种情况。KeyedIterable<arraykey, T>但是,即使arraykey是比 更通用的类型int,这也不起作用。例如,类型检查器抱怨以下代码:

<?hh // strict
class A {
   public static function foo(): KeyedIterable<arraykey, mixed> {
      return Vector{};
      /*
      Invalid return type (Typing[4110])
      This is an array key (int/string)
      It is incompatible with an int
      Considering that this type argument is invariant with respect to KeyedIterable
      */
   }
}

为什么我不能这样做?

4

1 回答 1

1

这是因为KeyedIterable不是只读的,所以不能采用子类型。

例如,A::foo()->toMap()将具有Map<arraykey, mixed>类型签名中的类型,但实际类型Map<int, mixed>

于 2016-04-02T22:05:32.007 回答