我想学习如何用以下简单的List扩展Filter类。但是,它不编译
extension on List {
void Filter<T>({bool Function(T)? predicate}) {
this.forEach((element) {
if (predicate?.call(element) ?? false) {
print(element);
}
});
}
}
void main() {
List.generate(10, (x) => x * x).Filter(predicate: (y) => y % 3 == 0);
}有以下错误:
dart/delegate.dart:12:62: Error: The operator '%' isn't defined for the class 'Object?'.
- 'Object' is from 'dart:core'.
Try correcting the operator to an existing operator, or defining a '%' operator.
List.generate(10, (x) => x * x).Filter(predicate: (y) => y % 3 == 0);
^如何解决这个问题?
发布于 2021-04-07 12:14:44
问题是扩展是在List (又名)上声明的。List<Object?>。这意味着你对元素的类型一无所知。
相反,您可能希望在List<T>上创建扩展并捕获T。
extension FilterListExtension<T> on List<T> {
void filter({bool Function(T)? predicate}) {
for (var element in this) {
if (predicate?.call(element) ?? false) {
print(element);
}
}
}
}然后您可以创建int的列表,并将其作为一个列表使用:
[for (var i = 0; i < 10; i++) i * i].filter(predicate((y) => y % 3 == 0));列表的静态类型与过滤器谓词的参数匹配是很重要的。对于List.generate(10, (x) => x * x),您创建一个List<Object?>,您应该编写List<int>.generate(10, (x) => x * x),或者使用上面的文字形式。
发布于 2021-04-05 17:41:53
看看这个:
extension on List {
void filter<T extends num>({bool Function(T)? predicate}) {
this.forEach((element) {
if (predicate?.call(element) ?? false) {
print(element);
}
});
}
}
void main() {
List.generate(10, (x) => x * x).filter<num>(predicate: (y) => y % 3 == 0);
}https://stackoverflow.com/questions/66957053
复制相似问题