user1756508 user1756508 - 1 month ago 10x
Dart Question

Dart generic class instantiation

In Dart are these two instantiation equivalent?

//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

Is there any problem using the version 2 (which I prefer because it is less verbose)?

Please note that I know that I could use:

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

but this is not the point I want to face with this question. Thanks.


No they are not equivalent, instantiations differ in runtime type and you may face surprises in code working with runtime types - like type checking.

new Map() is a shortcut to new Map<dynamic, dynamic>(), which means "mapping of whatever you want".

Testing slightly modified original instantiations:

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

update1: code in DartPad to play with.

update2: it seems strong mode will complain about map2 instantiation in future, see