How to work with Maps in Kotlin

Dina Kleper picture Dina Kleper · May 26, 2016 · Viewed 82k times · Source

The code below is creating a new map called nameTable, then adding an entry named example to it, then trying to print the name property of the Value.

When I run it, it seems that the plus operation didn't add a new entry to the map like I thought it would.

So what am I doing wrong?

class Person(name1: String, lastName1: String, age1: Int){
    var name: String = name1
    var lastName: String = lastName1
    var age: Int = age1
}

var nameTable: MutableMap<String, Person> = mutableMapOf()
var example = Person("Josh", "Cohen", 24)

fun main (args: Array<String>){
    nameTable.plus(Pair("person1", example))
    for(entry in nameTable){
        println(entry.value.age)
    }
}

While we're at it, I would love some examples of how to add, remove, and get an entry from a map.

Answer

voddan picture voddan · May 26, 2016

The reason for your confusion is that plus is not a mutating operator, meaning that it works on (read-only) Map, but does not change the instance itself. This is the signature:

operator fun <K, V> Map<out K, V>.plus(pair: Pair<K, V>): Map<K, V>

What you want is a mutating operator set, defined on MutableMap:

operator fun <K, V> MutableMap<K, V>.set(key: K, value: V)

So your code may be rewritten (with some additional enhancements):

class Person(var name: String, var lastName: String, var age: Int)

val nameTable = mutableMapOf<String, Person>()
val example = Person("Josh", "Cohen", 24)

fun main (args: Array<String>) {
    nameTable["person1"] = example

    for((key, value) in nameTable){
        println(value.age)
    }
}