Should [] on Map not be of type K -> V?

23 views
Skip to first unread message

Guyren Howe

unread,
May 24, 2022, 1:15:49 AM5/24/22
to Dart Misc
Since Map is K -> V [] surely should also be K -> V . It is currently Object? -> V?

Why is it ? and why is not from K?

This makes making a map-like thing more challenging, as `operator [](K key} => _store[key]` fail with:

''MemoryModel.[]' ('V? Function(K)') isn't a valid override of 'MapMixin.[]' ('V? Function(Object?)'). (Documentation)'

Nate Bosch

unread,
May 24, 2022, 2:20:53 PM5/24/22
to General Dart Discussion
The map will return a `null` from operator [] in the case of missing keys so the signature must have a nullable return type.

Throwing an exception on missing keys is a design we have discussed - there are tradeoffs between the designs and some authors prefer one over the other. Switching to exceptions would be a significant breaking change, and we don't have any plans to make that change.

--
For more ways to connect visit https://dart.dev/community
---
You received this message because you are subscribed to the Google Groups "Dart Misc" group.
To unsubscribe from this group and stop receiving emails from it, send an email to misc+uns...@dartlang.org.
To view this discussion on the web visit https://groups.google.com/a/dartlang.org/d/msgid/misc/86B23A9F-3285-419E-9CC2-95C1CEE8A8E1%40gmail.com.

James D. Lin

unread,
May 24, 2022, 2:57:20 PM5/24/22
to mi...@dartlang.org
I think the OP is asking more about why `Map.operator []` accepts `Object?` as an argument instead of `K`.  This has been brought up many times before:


(I stopped searching, but there almost certainly are many more older issues discussing it too.)

Also see https://github.com/dart-lang/linter/issues/1307 which is where something about it is most likely to be done.

- James

Reply all
Reply to author
Forward
0 new messages