Nir
12/14/2021, 7:50 PMMutableMap<T, Long>
is okay-ish for this, but incrementing feels very awkward
myCounts[something] = myCounts.getOrDefault(something, 0) + numberFound
I've generally found that updating state in maps can be a bit annoying so I do have a general helper function (which I think would be worth having in stdlib tbh)
fun <K, V> MutableMap<K, V>.update(k: K, transform: (V?) -> V) = set(k, transform(get(k)))
So it becomes
myCounts.update(k) { (it ?: 0) + numberFound
But still, end up repeating quite a bit. If there isn't a better way then I may just have a dedicated Counter (a la python) and possibly deal with both things with one stoneephemient
12/14/2021, 7:54 PMclass MutableLong(var value: Long)
val myCounts = mutableMapOf<T, MutableLong>()
myCounts.getOrPut(k) { MutableLong(0) }.value += number
as that also avoids repeatedly boxing Longephemient
12/14/2021, 7:54 PMLuke
12/14/2021, 8:52 PMupdate
fonction is basically the MutableMap.compute
function ignoring the first argument of the lambda. You can use map.compute(key) { _, value -> (value ?: 0) + numberFound }
. You also have a computeIfPresent
and computeIfAbsent
Nir
12/14/2021, 8:57 PMNir
12/14/2021, 8:57 PMephemient
12/14/2021, 9:19 PMephemient
12/14/2021, 9:21 PM