dart confusion on parameterized List

2019-08-03 08:13发布

问题:

Why this code no raise an error?

List<String> x;

void main() {
  x = [1,23,3,423,2];
  print(x);
}

Sorry for the newbie question, but i just start learning dart, and i ask this because of my understanding that the x can only contain a list ofString and should raise an exception due to the value not a list of String but a list of num. This is a bug, or?

回答1:

This is optional typing in action.

var x; // same as List<String> x
List<String> y;

main() {
  x = [1,2,3,4];
  y = x; // valid
  x = y; // valid
  print(x); // [1,2,3,4]
  print(y); // [1,2,3,4]
}

Whether you specify List<String> or var, your code will execute the same. The type annotations (List<String>) are used by the tools to verify your code.

A good article to read on the dartlang site is one about optional types.

Edit: Actually, this is also an interesting point about Lists. If you initialize a list using a literal list( eg, []), then you are actually creating a List(), eg:

main() {
  var x = new List(); 
  var y = [];
  print(x is List); // true
  print(y is List); // true
}

If, however, you want a typed list using generics, you must use the constructor syntax, eg:

main() {
  var x = new List<String>();
  print(x is List); // true
  print(x is List<String>); // true
  print(x is List<num>); // false
}


回答2:

Dart types are optional not static. So on runtime all type annonations is essentially replaced with var



标签: dart