Dart泛型类实例化



在Dart中这两个实例化是等价的吗?

//version 1
Map<String, List<Component>> map = new Map<String, List<Component>>();
//version 2
Map<String, List<Component>> map = new Map(); //type checker doesn't complain

使用版本2(我更喜欢它,因为它不那么冗长)有什么问题吗?

请注意,我知道我可以使用:

var map = new Map<String, List<Component>>();

但这不是我想面对这个问题的重点。谢谢。

不,它们不是等价的,实例化在运行时类型上是不同的,你可能会在使用运行时类型的代码中遇到意外——比如类型检查。

new Map()new Map<dynamic, dynamic>()的快捷方式,意思是"映射任何你想要的"。

测试稍微修改过的原始实例:

main(List<String> args) {
  //version 1
  Map<String, List<int>> map1 = new Map<String, List<int>>();
  //version 2
  Map<String, List<int>> map2 = new Map(); // == new Map<dynamic, dynamic>();
  // runtime type differs
  print("map1 runtime type: ${map1.runtimeType}");
  print("map2 runtime type: ${map2.runtimeType}");
  // type checking differs
  print(map1 is Map<int, int>); // false
  print(map2 is Map<int, int>); // true
  // result of operations the same
  map1.putIfAbsent("onetwo", () => [1, 2]);
  map2.putIfAbsent("onetwo", () => [1, 2]);
  // analyzer in strong mode complains here on both
  map1.putIfAbsent("threefour", () => ["three", "four"]);
  map2.putIfAbsent("threefour", () => ["three", "four"]);
  // content the same
  print(map1);
  print(map2);
}

update1:代码在DartPad玩。

update2:似乎强模式将来会抱怨map2实例化,参见https://github.com/dart-lang/sdk/issues/24712

最新更新