Closed as not planned
Description
when xs
is an Iterable
, the syntax for (var x in xs)
is available inside both imperative code and list/set/map literals.
it would be very useful to extend this syntax to maps.
examples:
for (var key, value in map) { // notice how 2 vars (key and value) are declared at once
print('$key: $value');
}
var otherMap = {
for (var key, value in map)
key + 1: value * 2
};
var list = [
for (var key, value in map)
key + value
];
var set = {
for (var key, value in map)
key + value
};
the current workarounds hurt readability and/or efficiency:
// hard to read
for (var ssnAndPerson in ssnToPerson.entries) {
print('${ssnAndPerson.key}: ${ssnAndPerson.value}');
}
// easy to read
for (var ssn, person in ssnToPerson) {
print('$ssn: $person');
}
// cons:
// - ok for imperative code, useless for list/set/map literals
// - can't use break, continue, return
ssnToPerson.forEach((ssn, person) {
print('$ssn: $person');
}
// another common workaround. cons:
// - repeats the map name
// - needs a pointless ! for null-safety
// - inefficiently looks up key in the map
// - no nice name for the value unless one wastes a line putting it into a local var
// which isn't an option inside a list/set/map literal
for (var ssn in ssnToPerson.keys) {
consume(ssnToPerson[ssn]!, ssn + offset);
}
// ugh!!
Map<int, int> plus1(Map<int, int> map) {
var otherMap = <int, int>{};
map.forEach((key, value) {
otherMap[key] = value + 1;
});
return otherMap;
}
// elegant
Map<int, int> plus1(Map<int, int> map) =>
{ for (var key, value in map) key: value + 1 };
// similar problems to "another common workaround" above
Map<int, int> plus1(Map<int, int> map) =>
Map.fromIterable(map.keys, value: (key) => map[key] + 1;