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?
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:.
Most helpful comment
It's type inference and implicit downcast.
When you do
method(['1', '2']);, the signature ofmethodasks for aList<Object>.So, the
['1', '2']is evaluated in a context where aList<Object>is expected, and it therefore creates aList<Object>containing two strings. Then, insidemethod, you try to downcast that to aList<String>. It fails because aList<Object>is-not-aList<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
methodas aList<Object>, which succeeds because aList<String>is-aList<Object>, andmethodthen down-casts it toList<String>again, which works because it is one.