buildMap

inline fun <K, V> buildMap(builderAction: MutableMap<K, V>.() -> Unit): Map<K, V>(source)

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.6

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
}

inline fun <K, V> buildMap(capacity: Int, builderAction: MutableMap<K, V>.() -> Unit): Map<K, V>(source)

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.6

Throws

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
}