如何在科特林使用地图 [英] How to work with Maps in Kotlin
问题描述
下面的代码创建一个名为nameTable
的新映射,然后向其中添加一个名为example的条目,然后尝试打印Value的name属性.
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.
推荐答案
您感到困惑的原因是plus
不是 变异运算符,意味着它适用于(只读) Map
,但不会更改实例本身.这是签名:
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>
您想要的是在MutableMap
上定义的变异运算符set
:
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)
}
}
这篇关于如何在科特林使用地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!