Is there a way to use `putAll` on a mutable map, p...
# codereview
k
Is there a way to use
putAll
on a mutable map, passing it another map and a value transformation function?
putAll
allows you to put all entries of another map into this map, but doesn't let you transform them on the fly.
mapTo
allows you to transform the entries but you can only write them to a Collection, not to a MutableMap. Is there a method that does what the commented-out line does?
Copy code
fun main() {
    val map1 = mapOf(1 to "one", 2 to "two", 3 to "three")
    val map2 = buildMap {
        put(4, "fourfour")
        put(5, "fivefive")

        // map1.mapTo(this) { (k, v) -> k to v + v } DOESN'T COMPILE

        // instead we have to use:
        putAll(map1.toMutableMap().apply { replaceAll { _, v -> v + v } })
        // or:
        putAll(map1.map { (k, v) -> k to v + v })
    }
    println(map2)
}
p
Copy code
putAll(map1.mapValues { (_, v) -> v + v })
?
k
Thanks, Paul. Your suggestion has led me to exactly what I'm looking for:
mapValuesTo
.
Copy code
map1.mapValuesTo(this) { (k, v) -> v + v }
p
Yeah, just realized you were more asking for direct mutation of the temp
buildMap
backing map