orangy
public inline fun <T, K, V> Iterable<T>.associateFoldBy(initial:V, keySelector: (T) -> K, operation: (V, T) -> V): Map<K,V> {
val destination = LinkedHashMap<K, V>()
for (element in this) {
val key = keySelector(element)
val current = destination.getOrPut(key) { initial }
destination.put(key, operation(current, element))
}
return destination
}
and use like
list.associateFoldBy(0, { it }, { it + 1 })