List of mixed types in Dart

Viewed 6709

This compiles in Dart:

var  data = ["abcd", 34, "ef", false];
int n = data[1];
print(n*2); // -> 68

I thought that list elements should be all of same type. And there is not implicit conversion from int to string or from bool to string in A):

 print(data[1] is int);    // -> true
 print(data[3] is bool);   // -> true
 print(data[1] is String); // -> false

EDIT: as Mattia pointed out the real error in the following lines is not related to swapping elements in the list initializatione but to copy/paste from A) to B) leaving the same index ([1])

And this does not compile ("abcd" swapped with 34):

var  data = [34, "abcd", "ef", false]; // -> type error
int n = data[1]; //EDIT: this is a non sense, should be data[0] (no error generated)
print(n*2);  

Reproducible DartPad

Why? Some sort of substitution principle at work?

1 Answers

If you want list to accept only one type you need to add a generic type for example:

var  data = <int>["abcd", 34, "ef", false]; // -> Error

by default if you don't add one the "most common type" (in this case Object) will be used and it will accept all variable types.

The second example does compile but gives a run-time error because data[1] is not an int but a String

Related