I have a question regrading `Grouping.fold`: I ass...
# getting-started
n
I have a question regrading `Grouping.fold`: I assumed the following 2 calls to return the same value, but the second returns
{a=[1, 3, 4, 5], b=[1, 3, 4, 5]}
instead of the expected
{a=[1, 3, 5], b=[4]}
. Looks the 2nd variant re-uses the initial value for all groups. What is a good use case for the 2nd variant?
Copy code
val g = listOf("a" to listOf(1, 3), "b" to listOf(4), "a" to listOf(5)).groupingBy { it.first }
g.fold({ _, _ -> mutableListOf<Int>() }, { _, acc, item -> acc.addAll(item.second); acc })
g.fold(mutableListOf<Int>(), { acc, item -> acc.addAll(item.second); acc })
r
The second variant can be used whenever the initial value is immutable. In that case there's no need to recreate a new instance for every group