Sdk: Directly passing a List to a method fails but wrapping it into a variable works.

Created on 26 May 2020  路  3Comments  路  Source: dart-lang/sdk

Some magic is going on which is shaking my basics:

void main() {
  method(['1', '2']); // fails

  final list = ['1', '2'];
  method(list); // works
}

void method(List<Object> objects) {
  List<String> strings = objects;
}

Can anyone explain the reason behind this magic?

type-question

Most helpful comment

It's type inference and implicit downcast.

When you do method(['1', '2']);, the signature of method asks for a List<Object>.
So, the ['1', '2'] is evaluated in a context where a List<Object> is expected, and it therefore creates a List<Object> containing two strings. Then, inside method, you try to downcast that to a List<String>. It fails because a List<Object> is-not-a List<String>.

When you write final list = ['1', '2']; you evaluate ['1', '2'] in a context with no type expectation.
The list literal contains two strings, and absent any other type hint, it creates a List<String>.
You then pass that to method as a List<Object>, which succeeds because a List<String> is-a List<Object>, and method then down-casts it to List<String> again, which works because it is one.

All 3 comments

It's type inference and implicit downcast.

When you do method(['1', '2']);, the signature of method asks for a List<Object>.
So, the ['1', '2'] is evaluated in a context where a List<Object> is expected, and it therefore creates a List<Object> containing two strings. Then, inside method, you try to downcast that to a List<String>. It fails because a List<Object> is-not-a List<String>.

When you write final list = ['1', '2']; you evaluate ['1', '2'] in a context with no type expectation.
The list literal contains two strings, and absent any other type hint, it creates a List<String>.
You then pass that to method as a List<Object>, which succeeds because a List<String> is-a List<Object>, and method then down-casts it to List<String> again, which works because it is one.

Thank you, and that makes sense!

However, I am bit disappointed by Dart team members, you have a team of great developers, why don't you allow some of them to answer questions on SO, I know there is one great person @jamesderlin who keeps on answering my questions but he is also a human being, he may sometimes forget to read all the Dart questions (that actually need answer from expert like you guys).

Or should I start posting questions here on Github issues because there exists an answer to all the questions which only you guys can answer and not the other SO users (non-Google members). So, in case my question isn't answered on SO within 2 days, is this the right place to ask? By the way here is the question link

Some of us read and answer on Stack Overflow as well, but we are only human too :smile:.

Was this page helpful?
0 / 5 - 0 ratings