Reputation: 261
What is the difference between the following two statements:
List names = ["John", "Robert", "James"];
List<String> names = ["John", "Robert", "James"];
Upvotes: 0
Views: 90
Reputation: 31259
Dart will in the first example assume the type should be List<dynamic>
since you have just told the type system that you want a List
without any specific restrictions.
In the second example, the created list are getting the type List<String>
since you have provided a restriction of the type of elements you want in the list.
Another example would be the following:
var names = ["John", "Robert", "James"]; // or final instead of var
Here we are letting Dart automatically determine the most restrictive type possible. In this case, the names
are going to be automatically typed List<String>
.
You can see this if you print the runtimeType
of each declared list:
void main() {
List names1 = ["John", "Robert", "James"];
print(names1.runtimeType); // List<dynamic>
List<String> names2 = ["John", "Robert", "James"];
print(names2.runtimeType); // List<String>
var names3 = ["John", "Robert", "James"];
print(names3.runtimeType); // List<String>
}
Upvotes: 1