dart - 如何为 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;
}
}
}
我不确定我在这里做错了什么?
解决方案
在第一个示例中,您实际上是在踢自己的脚。方法签名中的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;
}
}
}
推荐阅读
- prolog - prolog 中的分辨率求解器
- javascript - 在维护顶部组件的状态时避免 React Hooks 重新渲染?
- javascript - 缩短我的代码(将 3 个功能变成 1 个)使其停止工作。我究竟做错了什么?
- ios - 有没有办法优化 XML Parse 和 Magical Record Inserts?
- embedded - STM32 SPI 仅通信回显发送数据
- woocommerce - 如何获取当前的过滤器产品数量?
- c# - 按下按钮时的验证
- android - 数据不会从活动转移到片段
- c# - 像这样使用实体框架向表中添加条目是不好的做法吗?
- laravel - Laravel 按需广播