groupByTo<K, M extends KtMutableMap<K, KtMutableList>> method

M groupByTo<K, M extends KtMutableMap<K, KtMutableList>>(
  1. M destination,
  2. K keySelector(
    1. T
    )
)

Groups elements of the original collection by the key returned by the given keySelector function applied to each element and puts to the destination map each group key associated with a list of corresponding elements.

destination is not type checked by the compiler due to https://github.com/dart-lang/sdk/issues/35518, but will be checked at runtime. C actually is expected to be C extends KtMutableCollection<T>

Implementation

// TODO Change to `M extends KtMutableMap<K, KtMutableList<T>` once https://github.com/dart-lang/sdk/issues/35518 has been fixed
M groupByTo<K, M extends KtMutableMap<K, KtMutableList<dynamic>>>(
    M destination, K Function(T) keySelector) {
  assert(() {
    if (destination is! KtMutableMap<K, KtMutableList<T>> &&
        mutableMapFrom<K, KtMutableList<T>>() is! M) {
      throw ArgumentError("groupByTo destination has wrong type parameters."
          "\nExpected: KtMutableMap<K, KtMutableList<$T>, Actual: ${destination.runtimeType}"
          "\ndestination (${destination.runtimeType}) entries aren't subtype of "
          "map ($runtimeType) entries. Entries can't be copied to destination."
          "\n\n$kBug35518GenericTypeError");
    }
    return true;
  }());
  for (final element in iter) {
    final key = keySelector(element);
    final list = KtMutableMapExtensions(destination)
        .getOrPut(key, () => mutableListOf<T>());
    list.add(element);
  }
  return destination;
}