adapt<K, V> method
Converts the given source or this into a strongly-typed Map<K, V>.
- If
sourceis HashMap or collection.HashMap, keys and values are cast toKandV. - If
sourceis a native Map, a typed copy is returned. - Otherwise, throws IllegalArgumentException.
Example:
final adaptable = AdaptableMap();
adaptable['a'] = 1;
final typedMap = adaptable.adapt<String, int>(); // Map<String, int>
Implementation
Map<K, V> adapt<K, V>([Object? source]) {
source ??= this;
if (source is HashMap) {
final map = HashMap<K, V>();
for (var e in source.entries) {
map[e.key as K] = e.value as V;
}
return map;
}
if (source is collection.HashMap) {
final map = collection.HashMap<K, V>();
for (var e in source.entries) {
map[e.key as K] = e.value as V;
}
return map;
}
if (source is Map) {
return Map<K, V>.from(source);
}
throw IllegalArgumentException('Cannot adapt $source to Map<$K, $V>');
}