我很困惑为什么以下 Dart 代码会生成运行时错误:
class Store<ID, T> {
Store({Map<ID, T> values = const {}}) : _cache = values;
final Map<ID, T> _cache;
void put(ID id, T value) {
_cache[id] = value;
}
}
...
final foo = Store<int, Store<int, String>>();
// Runtime error inside `Store.put`:
// TypeError: 7: type 'int' is not a subtype of type 'Never'
foo.put(7, Store<int, String>());
如果我像这样直接使用
Map
,这不是问题:
final foo = Map<int, Map<int, String>>();
foo[7] = Map<int, String>());
我需要了解一些关于 Dart 泛型的知识才能使
Store
工作吗?
我认为这是由
const {}
造成的,因为它有Map<Never, Never>
你可以试试这个:
class Store<ID, T> {
Store() : _cache = {};
final Map<ID, T> _cache;
void put(ID id, T value) {
_cache[id] = value;
}
}