is there a variant of `associateBy` that would thr...
# getting-started
p
is there a variant of
associateBy
that would throw if a key should have more than one value?
🚫 1
t
You could write such an extension :
Copy code
inline fun <T, K> Iterable<T>.associateUniquelyBy(crossinline keyProvider: (T) -> K): Map<K, T> {
    return groupingBy(keyProvider).aggregate { key, accumulator, element, first ->
        if (first) element else error("Duplicated key: an element is already associated to the key $key")
    }
}
1