How to work with Maps in Kotlin
Solution 1:
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)
}
}
Solution 2:
The plus-method on Map
creates a new map that contains the new entry. It does not mutate the original map. If you want to use this method, you would need to do this:
fun main() {
val table = nameTable.plus(Pair("person1", example))
for (entry in table) {
println(entry.value.age)
}
}
If you want to add the entry to the original map, you need to use the put
method like in Java.
This would work:
fun main() {
nameTable.put("person1", example)
for (entry in nameTable) {
println(entry.value.age)
}
}
To get and remove entries from the MutableMap
, you can use this:
nameTable["person1"] // Syntactic sugar for nameTable.get("person1")
nameTable.remove("person1")