diff --git a/pkgs/collection/CHANGELOG.md b/pkgs/collection/CHANGELOG.md index 1aaf3527..aa866d53 100644 --- a/pkgs/collection/CHANGELOG.md +++ b/pkgs/collection/CHANGELOG.md @@ -1,5 +1,6 @@ ## 1.20.0-wip +- `CanonicalizedMap.cast` returns a view of the public keys and values. - Adds `separated` and `separatedList` extension methods to `Iterable`. - Adds `separate` extension method to `List` - Add `IterableMapEntryExtension` for working on `Map` as a list of pairs, using diff --git a/pkgs/collection/lib/src/canonicalized_map.dart b/pkgs/collection/lib/src/canonicalized_map.dart index 753ebe61..cd845838 100644 --- a/pkgs/collection/lib/src/canonicalized_map.dart +++ b/pkgs/collection/lib/src/canonicalized_map.dart @@ -106,7 +106,11 @@ class CanonicalizedMap implements Map { ); @override - Map cast() => _base.cast(); + Map cast() { + // `_base` stores canonical keys and `MapEntry`s, not the public `K`/`V` + // view. Casting that storage makes lookups fail with a cast error. + return Map.castFrom(this); + } @override void clear() { diff --git a/pkgs/collection/test/canonicalized_map_test.dart b/pkgs/collection/test/canonicalized_map_test.dart index ae81688e..5b05d20a 100644 --- a/pkgs/collection/test/canonicalized_map_test.dart +++ b/pkgs/collection/test/canonicalized_map_test.dart @@ -159,6 +159,14 @@ void main() { test('cast returns a new map instance', () { expect(map.cast(), isNot(same(map))); }); + + test('cast preserves lookups on the public key and value types', () { + map.addAll({'01': 'value 01', '2': 'value 2'}); + final casted = map.cast(); + expect(casted['01'], 'value 01'); + expect(casted['1'], 'value 01'); + expect(casted.length, 2); + }); }); group('CanonicalizedMap builds an informative string representation', () {