Is there no type checking in a list of maps in dar

2019-07-04 11:15发布

问题:

For example if you have the list:

List<Map<String,int>> list =  <Map<String,int>>[
    {"string1": 44},
    {"string2" : "string in place of int"}
];

or

List<Map<String,int>> list =  new List<Map<String,int>>();
list.addAll([
    {"string1": 44},
    {"string2" : "string in place of int"}]
);

Shouldn't there be a warning for "string in place of int" ?

回答1:

To get a warning from the analyzer or in DartEditor you need to write it like

List<Map<String,int>> list =  <Map<String,int>>[
    <String,int>{"string1": 44},
    <String,int>{"string2" : "string in place of int"}
];


回答2:

Types are not used by Dart unless you execute your code in checked mode.

When Dart is not in checked mode (which should be the case in production) having no types at all, wrong types or right types makes no difference (no error, no speed gain).



回答3:

In Dart the static checker does not complain about every possible type violation because there is a chance the code is correct. At runtime when an illegal operation is done you get an exception.

When I use:

{"string2" : "string in place of int"}

I make a map: Map<dynamic,dynamic>, dynamic shuts up the static checker.

Dart allows this code to run because down-assignments may be valid and Dart is optimistic that you know what you’re doing.

So my Map could be Map<String,int> then it's correct, if not an exception is thrown.



标签: dart