Home > Enterprise >  The difference between writing values (list, map, set...)
The difference between writing values (list, map, set...)

Time:09-29

The difference between writing values

in List :

List list = <int>[1, 2, 3];

List list<int> = [1, 2, 3];

List<int> list = <int>[1, 2, 3];

in Set :

Set set = <int>{1, 2, 3};

Set<int> set = {1, 2, 3};

Set<int> set = <int>{1, 2, 3};

in Map :

Map<String, String> map = {'key': 'value'};

Map map = <String, String>{'key': 'value'};

Map<String, String> map = <String, String>{'key': 'value'};

the difference or Which one is better ?

CodePudding user response:

List list = <int>[1, 2, 3];

List list<int> = [1, 2, 3];

List<int> list = <int>[1, 2, 3];

Version 2 is not legal syntax. I will presume that you meant:

List<int> list = [1, 2, 3];

which creates a List<T> object where T will be inferred from the declared type of List<int> from the left-hand-side. Ultimately it will be the same as version number 3.

Version 1 is different from the rest. Omitting the generic type argument means that Dart will assume it to be the least-constrained type allowed for that type parameter. For most generics, including List, that means dynamic. That is:

List list = <int>[1, 2, 3];

is identical to:

List<dynamic> list = <int>[1, 2, 3];

which creates an object with a runtime type of List<int>, but the static (known at compile-time) type of the list variable is List<dynamic>.

Here are some examples to demonstrate the difference:

List<String> strings = ['foo'];

List list1 = <int>[1, 2, 3];
list1.add('foo'); // Compiles but will fail at runtime.
list1 = strings; // OK

List<int> list2 = <int>[1, 2, 3];
list2.add('foo'); // Compilation error.
list2 = strings; // Compilation error.

I'll add some other variations:

List list4 = [1, 2, 3];
var list5 = [1, 2, 3];

list4 will have both a static type and a runtime type of List<dynamic>. Since no explicit type argument is given for the list literal, the type will be inferred from the declared type from the left-hand-side (List, which as noted above is shorthand for List<dynamic>.)

list5 will have both a static type and a runtime type of List<int>. Since no explicit type argument is given for the list literal, and no explicit type is declared, the element type will be inferred to be the common base type of 1, 2, and 3, which is int.

As for what you should use, Effective Dart recommends against using redundant types, so following that, you should use:

var list = [1, 2, 3];

Note that doing so avoids the implicit use of dynamic that would occur if you accidentally used an incomplete generic type.

All of the above also applies to Set, Map, and other generic types.

  • Related