Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I assign List<dynamic> to a List<String>?

Tags:

dart

I am getting confused around how the type checking works for dart. As shown, assigning a general List<dynamic> to a List<String> is OK. That essentially means I can assign any content in that list, not just String. Why is that?

void main() {
  List<String> a;
  a = [1];                 // pass
  a = new List<int>();     // fail
  a = 1;                   // fail
  a = new List<String>();  // pass
  a.add(1);                // fail
}
like image 623
tusj Avatar asked Oct 23 '25 17:10

tusj


1 Answers

The dynamic type is special. It really means "turn off all type checking for this, I know what I'm doing".

In your example, you assign a List<dynamic> instance to a List<String> variable. The static type checker sees: List to list, that's ok, and the type parameter is dynamic, so I'll just not check that at all, the programmer must know that he is doing.

Whenever you use dynamic as a type, or as part of a type, you are taking full responsibility for the typing being correct. The system will let you do whatever you want.

Even without dynamic, the Dart type system isn't safe. That means that you can create programs with no static type warnings which still fail with a type error at runtime. Most languages have that problem, actually, as soon as they contain parameterized types with either co- or contra-variant subtyping. Or casts.

like image 60
lrn Avatar answered Oct 25 '25 13:10

lrn