Reason for Map.fromIterable not being more type specific

56 views
Skip to first unread message

Maximilian Domröse

unread,
Feb 6, 2025, 10:54:50 AMFeb 6
to Dart Misc
Hello,

Hope this is the right group for my question. Why is there no generic type parameter for Map.fromIterable? For example, why is it

Map<K,V>.fromIterable(
  Iterable<dynamic> iterable, {
  K Function(dynamic)? key,
  V Function(dynamic)? value,
})

instead of it being

Map<K,V>.fromIterable<T>(
  Iterable<T> iterable, {
  K Function(T)? key,
  V Function(T)? value,
})

I understand that factory functions cannot have generic type parameters, but why not make it a generic static function instead? What was the reason for this choice? Would it be worse performance wise to have a generic static function?

Thanks so much,

Maximilian Domröse

Bob Nystrom

unread,
Feb 6, 2025, 6:20:32 PMFeb 6
to mi...@dartlang.org
I believe the answer is "backwards compatibility".

Before 2.0, Dart didn't support generic methods, only generic classes. The Map.fromIterable() constructor has been around since before 2.0. Changing it to be a static method with a type parameter would be a breaking API change because any class that extends Map and calls fromIterable() as its superclass constructor would break.

Now that we support control flow in collection literals, instead of using Map.fromIterable(), I would do:

{for (var v in iterable) key(v): value(v)}

That will give you a more precise type for the element and will often be shorter too.

Cheers!

– bob

--
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 visit https://groups.google.com/a/dartlang.org/d/msgid/misc/9a167eee-5662-41ca-b8bb-ac7d7b485126n%40dartlang.org.

James D. Lin

unread,
Feb 6, 2025, 6:40:50 PMFeb 6
to mi...@dartlang.org
Perhaps the Map<K, V>.fromIterable documentation should be updated to recommend that people use a collection literal instead. (That wouldn't work as nicely if someone wanted to create a SplayTreeMap though.)

- James

Bob Nystrom

unread,
Feb 6, 2025, 8:56:19 PMFeb 6
to mi...@dartlang.org
Reply all
Reply to author
Forward
0 new messages