Klitos Kyriacou
08/03/2022, 3:45 PMputAll
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)
}
Paul Griffith
08/03/2022, 3:51 PMputAll(map1.mapValues { (_, v) -> v + v })
?Klitos Kyriacou
08/03/2022, 3:55 PMmapValuesTo
.
map1.mapValuesTo(this) { (k, v) -> v + v }
Paul Griffith
08/03/2022, 3:55 PMbuildMap
backing map