In some cases this lack can cause repeated code an...
# announcements
n
In some cases this lack can cause repeated code and work in later applying fold etc to the Grouping
Here's an example that motivated this question, there isn't much extra "work" really but a bit of extra code
Copy code
fun List<Food>.toAllergenPossibilities() = asSequence()
    .flatMap { food -> food.allergens.map { it to food.ingredients } }
    .groupingBy { (allergen, _) -> allergen }
    .foldTo(mutableMapOf(),
        initialValueSelector = { _, (_, ingredients) -> ingredients.toMutableSet() }) { _, set, (_, ingredients) ->
        set.apply { retainAll(ingredients) }
    }
So, in this example, in foldTo, we need to destructure ingredients out of the value twice, even though allergen is already our key
Instead we could write it like this:
Copy code
fun List<Food>.toAllergenPossibilities() = asSequence()
    .flatMap { food -> food.allergens.map { it to food.ingredients } }
    .groupingBy { (allergen, _) -> allergen }
    .mapValues { it.second }
    .foldTo(mutableMapOf(),
        initialValueSelector = { _, ingredients -> ingredients.toMutableSet() }) { _, set, ingredients ->
        set.apply { retainAll(ingredients) }
    }
Anyway can implement this myself I suppose, maybe the standard library would be interested in it
unfortunately this is pretty hard to implement without a lot of overhead, given how the Grouping interface is specified and the extension functions are written
I created an issue and summarized the problem here: https://youtrack.jetbrains.com/issue/KT-44503
If anyone knows why Grouping has this iterator + keyOf interface, instead of simply providing an iterator<Pair<T, K>>, I'd be curious to know
i
Iterator<Pair<T, K>>
requires to allocate a pair for every element, this would significantly increase memory traffic of
groupingBy
operations.
n
Fair enough, that makes sense
Then, is the lack of
valueOf
also a conscious decision for perf reasons or was it simply not considered?