【问题标题】:Accessing the values inside a map in Kotlin在 Kotlin 中访问地图中的值
【发布时间】:2018-05-03 03:31:05
【问题描述】:

我无法访问我在此动物对象中构建的字典/地图中的值:

object Animals {
var animalInfo = mutableMapOf<String,Any>()
init {
    animalInfo["Animal"] = mutableListOf("description" to "Large Mammal", "name" to "Elephant", "highlights" to arrayListOf("Long Trunk", "Flappy Ears", "Ivory Tusks"))
    }
}    

Swift 是我的第一门语言,我尝试访问这样的值,但没有使用可选绑定:

 val dataDict = Animals.animalInfo
        val animal = dataDict["Animal"]
        println(animal["description"])
        println(animal["name"])
        println(animal["highLights"])

所有 println 行都有一个未解决的引用错误。如何正确访问 mutableMapOf() 中的值?

【问题讨论】:

  • 仍然无法编译。 animalInfomoduleInfo.

标签: java dictionary hashmap kotlin key-value


【解决方案1】:

改变这一行:

var animalInfo = mutableMapOf<String,Any>()

进入

var animalInfo = mutableMapOf<String,MutableMap<String, out Any>>()

改变

val module = dataDict["Animal"]

进入

val module = dataDict["Animal"]!!

mutableListOf 更改为mutableMapOf 应该可以解决这个问题(总共3 个更改)。

【讨论】:

  • 等我也找到了,给我一分钟
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-07
  • 2020-08-28
  • 2022-01-23
相关资源
最近更新 更多