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

dart

Solution

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.

Problem

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 } ```

Original source