adapt<K, V> method

Map<K, V> adapt<K, V>([
  1. Object? source
])

Converts the given source or this into a strongly-typed Map<K, V>.

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>');
}