evkaky
05/20/2021, 10:10 AMval map = mutableMapOf("key1" to 1)
map["key1"] += 2
Why Is it not possible to use increment in such a way?hho
05/20/2021, 10:19 AMmap["key1"]
gives you an instance of Int
, which is immutable. You can't assign a new value to an Int
.evkaky
05/20/2021, 10:21 AMRoukanken
05/20/2021, 10:30 AMInt?.plusAssign(Int)
because it does not desugar into map.get(a) = map.get(a) + b
but into map.get(a).plusAssign(b)
hho
05/20/2021, 10:33 AMRoukanken
05/20/2021, 10:33 AMget(a)
returns nullable, so that's another issue there đUlrik Rasmussen
05/20/2021, 11:44 AMm.compute("key1") { _, i -> i?.let { it + 1 } }
Ulrik Rasmussen
05/20/2021, 11:46 AMm.computeIfPresent("key1") { _, i -> i + 1 }
evkaky
05/20/2021, 11:47 AMmap["key1"]! += 2
Ulrik Rasmussen
05/20/2021, 11:48 AMmap[k]
is just sugar for map.get(k)
Travis Griggs
05/20/2021, 4:42 PMephemient
05/20/2021, 6:06 PMfun <K, V> MutableMap<K, V>.findEntry(key: Key): MutableMap.MutableEntry<K, V>?
then you could
m.findEntry("key1")?.let { it.setValue(it.value + 2) }
but sadly there is no such APIUlrik Rasmussen
05/21/2021, 6:38 AMMichael Böiers
05/21/2021, 2:58 PMfun <K, V> MutableMap<K, V>.replace(key: K, value: (V) -> V) =
compute(key) { _, old -> if (old == null) null else value(old) }
val map = mutableMapOf("a" to 42)
map.replace("a") { it + 1 }
println(map)
ephemient
05/21/2021, 3:22 PMMichael Böiers
05/21/2021, 3:30 PMMichael Böiers
05/21/2021, 4:17 PMfun <K, V> MutableMap<K, V>.replace(key: K, value: (V) -> V) =
computeIfPresent(key) { _, old -> value(old) }
val map = mutableMapOf("a" to 42)
map.replace("a") { it + 1 }