Maps in Kotlin

Maps are Kotlin’s built-in associative data type (sometimes called hashes or dicts in other languages).

To create an empty map, use the built-in mutableMapOf<KeyType, ValueType>():

fun main() {
    val m: MutableMap<String, Int> = mutableMapOf()

Set key/value pairs using typical name[key] = val syntax.

    m["k1"] = 7
    m["k2"] = 13

Printing a map with e.g. println will show all of its key/value pairs.

    println("map: $m")

Get a value for a key with name[key].

    val v1: Int? = m["k1"]
    println("v1: $v1")

If the key doesn’t exist, the operation returns null in Kotlin.

    val v3: Int? = m["k3"]
    println("v3: $v3")

The built-in size property returns the number of key/value pairs when called on a map.

    println("len: ${m.size}")

To remove key/value pairs from a map, use the remove function.

    m.remove("k2")
    println("map: $m")

To remove all key/value pairs from a map, use the clear function.

    m.clear()
    println("map: $m")

The optional second return value when getting a value from a map indicates if the key was present in the map. This can be used to disambiguate between missing keys and keys with null values. Here we didn’t need the value itself, so we just check for the presence.

    val prs: Boolean = m.containsKey("k2")
    println("prs: $prs")

You can also declare and initialize a new map in the same line with this syntax.

    val n: Map<String, Int> = mapOf("foo" to 1, "bar" to 2)
    println("map: $n")

Note that Kotlin does not have a built-in map utility package like maps, but you can use standard collection functions for most operations.

    val n2: Map<String, Int> = mapOf("foo" to 1, "bar" to 2)
    if (n == n2) {
        println("n == n2")
    }
}

Note that maps appear in the form map[k=v, k=v] when printed with println.

$ kotlinc Maps.kt -include-runtime -d Maps.jar
$ java -jar Maps.jar
map: {k1=7, k2=13}
v1: 7
v3: null
len: 2
map: {k1=7}
map: {}
prs: false
map: {foo=1, bar=2}
n == n2

Next example: Functions.