Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map operator [] is not type-safe #43517

Closed
devxpy opened this issue Sep 22, 2020 · 3 comments
Closed

Map operator [] is not type-safe #43517

devxpy opened this issue Sep 22, 2020 · 3 comments
Labels
type-question A question about expected behavior or functionality

Comments

@devxpy
Copy link

devxpy commented Sep 22, 2020

The following code compiles successfully, but in my mind, it should have not -

void main() {
  Map<int, String> myIntMap = {5: "hello!"};
  print(myIntMap["5"]);
}

Output -

null

At compile time, Is there any way to make dart ensure that the type of key that I'm passing is the correct type for that Map?

As one can imagine, this kind of mistake is very easy to make, and also easily preventable at compile time. (We just encountered a hard to track bug in our app because of it!)

dartpad

@lrhn
Copy link
Member

lrhn commented Sep 22, 2020

There is no way to avoid an incompatible type being allowed, while also allowing a Map<String, String> to be used as a Map<Object, Object>. Dart has covariant generics, so the string map is assignable to the object map type. By allowing any value to be used as key in lookup (and a few other methods), you can use the map at the supertype, as long as you only use it for reading. Writing will still necessarily throw.

There are some lints for similar situations (iterable_contains_unrelated_type, list_remove_unrelated_type), but nothing for map indexing.

@lrhn lrhn added the type-question A question about expected behavior or functionality label Sep 22, 2020
@kevmoo
Copy link
Member

kevmoo commented Sep 22, 2020

I agree this is weird. We should do something like #57844

@lrhn – there's no action for us here, right?

@devxpy
Copy link
Author

devxpy commented Sep 22, 2020

Thanks, the linter issue seems like a nice to have :)

@devxpy devxpy closed this as completed Sep 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-question A question about expected behavior or functionality
Projects
None yet
Development

No branches or pull requests

3 participants