首页 > 解决方案 > 如何为 Dart 静态扩展指定泛型类型?

问题描述

我正在尝试在 Iterable 上创建一个静态扩展,如下所示:


extension IterableExtensions<T> on Iterable<T> {
  Iterable<E> mapIndexed<E, T>(E Function(int index, T item) f) sync* {
    var index = 0;

    for (final item in this) {
      yield f(index, item);
      index = index + 1;
    }
  }
}

但这给了我一个错误: The argument type 'T' can't be assigned to the parameter type 'T'.

而如果我转换编译器很高兴:

extension IterableExtensions on Iterable{
  Iterable<E> mapIndexed<E, T>(E Function(int index, T item) f) sync* {
    var index = 0;

    for (final item in this) {
      yield f(index, item as T);
      index = index + 1;
    }
  }
}

我不确定我在这里做错了什么?

标签: dart

解决方案


在第一个示例中,您实际上是在踢自己的脚。方法签名中的T定义覆盖了T扩展签名中的。如果将其中一个更改为其他内容,您可以更清楚地看到发生了什么:

extension IterableExtensions<U> on Iterable<U> {
  Iterable<E> mapIndexed<E, T>(E Function(int index, T item) f) sync* {
    var index = 0;

    for (final item in this) {
      yield f(index, item);
      index = index + 1;
    }
  }
}

// Error: The argument type 'U' can't be assigned to the parameter type 'T'.

解决方法是T从方法签名中删除:

extension IterableExtensions<T> on Iterable<T> {
  Iterable<E> mapIndexed<E>(E Function(int index, T item) f) sync* {
    var index = 0;

    for (final item in this) {
      yield f(index, item);
      index = index + 1;
    }
  }
}

推荐阅读