我使用 .fold() 方法对列表求和时出错:
List<int> listInt = [1, 2, 3, 4, 5, 6];
int sumList = listInt.fold(0, (p, c) => p + c);
// First Print
print(sumList);
// Second Pring
print(listInt.fold(0, (p, c) => p + c));
Run Code Online (Sandbox Code Playgroud)
打印 sumList 完全没问题,但是当我打印相同的操作时,我收到编译错误:
The operator '+' can't be unconditionally invoked because the receiver can be 'null'.
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?
Dart 类型系统不够智能,无法猜测正确类型的情况。在你的第二行中发生的事情是认为fold你想要Object?返回所以p变成了Object?。
在第一个示例中,Dart 类型系统根据int您的情况的预期返回类型来猜测类型。但因为printExpects Object?,你实际上没有得到你期望的类型。
原因是 Dart 类型系统并不真正理解根据第一个参数的类型定义作为第二个参数的方法的返回类型的概念。fold如果我们没有类型化的输出,那么这里经常会出现问题。
我们可以通过将第二行更改为:来强制它理解我们想要的内容:
print(listInt.fold<int>(0, (p, c) => p + c));
Run Code Online (Sandbox Code Playgroud)
它应该按照你想要的方式工作。
| 归档时间: |
|
| 查看次数: |
268 次 |
| 最近记录: |