buildMap
Builds a new read-only Map by populating a MutableMap using the given builderAction and returning a read-only map with the same key-value pairs.
The map passed as a receiver to the builderAction is valid only inside that function. Using it outside of the function produces an unspecified behavior.
Entries of the map are iterated in the order they were added by the builderAction.
The returned map is serializable (JVM).
Since Kotlin
1.6Samples
fun main() {
//sampleStart
val x = mapOf('b' to 2, 'c' to 3)
val y = buildMap<Char, Int>(x.size + 2) {
put('a', 1)
put('c', 0)
putAll(x)
put('d', 4)
}
println(y) // {a=1, c=3, b=2, d=4}
//sampleEnd
}
Builds a new read-only Map by populating a MutableMap using the given builderAction and returning a read-only map with the same key-value pairs.
The map passed as a receiver to the builderAction is valid only inside that function. Using it outside of the function produces an unspecified behavior.
capacity is used to hint the expected number of pairs added in the builderAction.
Entries of the map are iterated in the order they were added by the builderAction.
The returned map is serializable (JVM).
Since Kotlin
1.6Throws
if the given capacity is negative.
Samples
fun main() {
//sampleStart
val x = mapOf('b' to 2, 'c' to 3)
val y = buildMap<Char, Int>(x.size + 2) {
put('a', 1)
put('c', 0)
putAll(x)
put('d', 4)
}
println(y) // {a=1, c=3, b=2, d=4}
//sampleEnd
}