我正在给柯特林打电话,我遇到了一个小问题,我解决不了. 当我具有以下 struct 时,我可以将元素放入 map 中:

val map = HashMap<String, String>()
map["asd"] = "s"
map.put("34", "354")

然而,当我用Map界面创建 map 时,我只能读取它们,我做错了什么?

val map: Map<String, String> = HashMap<String, String>();
map.put("24", "34") //error
map["23"] = "23" //error

Or maybe I'm confusing something about interfaces in Kotlin ?

推荐答案

In the first example map gets the type of HashMap, in the second example you cast it to the Interface Map.

map 是只读 map ,没有put/set,请参见here

In order to be able to edit the map, you should use MutableMap

Kotlin相关问答推荐

有什么原因,我得到一个空相关的错误在这个代码

在Kotlin中处理结果的高阶函数

可以从背景图像中点击图标吗?

在Spring Boot应用程序中使用网络请求功能将关键字挂起作为冗余

如何检测一个值是否是Kotlin中的枚举实例?

kotlin - 挂起简单方法调用链时可能存在冗余分支

在Kotlin lambda的参数中如何指定函数类型?

区分函数和扩展

如何在 kotlin 的片段类中更改 ActionBar 标题?

如何在 kotlin 中生成 json 对象?

如何设置两列recyclerview?

Kotlin get字段注释始终为空

使用 Paging 3 时保存并保留 LazyColumn 滚动位置

为什么 Kotlin Pair 中的条目不可变?

使用导航组件在不同的图形之间导航

Kotlin out-projected 类型禁止使用

kotlin 委托有什么用?

Kotlin中保留的关键字是什么?

Kotlin数据类打包

如何将vararg作为数组传递给Kotlin中的函数?