buildMap

Common
JVM
JS
Native
1.3
@ExperimentalStdlibApi inline fun <K, V> buildMap(
    builderAction: MutableMap<K, V>.() -> Unit
): Map<K, V>

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.



fun main(args: Array<String>) {
//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
}
Common
JVM
JS
Native
1.3
@ExperimentalStdlibApi inline fun <K, V> buildMap(
    capacity: Int,
    builderAction: MutableMap<K, V>.() -> Unit
): Map<K, V>

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.



fun main(args: Array<String>) {
//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
}

Exceptions

IllegalArgumentException - if the given capacity is negative.