https://kotlinlang.org logo
Title
k

Klitos Kyriacou

08/03/2022, 3:45 PM
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?
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

Paul Griffith

08/03/2022, 3:51 PM
putAll(map1.mapValues { (_, v) -> v + v })
?
k

Klitos Kyriacou

08/03/2022, 3:55 PM
Thanks, Paul. Your suggestion has led me to exactly what I'm looking for:
mapValuesTo
.
map1.mapValuesTo(this) { (k, v) -> v + v }
p

Paul Griffith

08/03/2022, 3:55 PM
Yeah, just realized you were more asking for direct mutation of the temp
buildMap
backing map