为什么我不能直接使用 Hashmap,为什么要转换它

Why can't i use Hashmap directly ,why casting it

我正在尝试从 Firebase 检索数据,所以我正在使用 Hashmap,但我想知道为什么要转换 Hashmap,为什么不能直接使用它。 请给出深入浅出的语言回答(应该是Kotlin)

代码如下:

var map = snapshot.getValue() as Hashmap<String,String>

DataSnapshot#getValue() method returns an object of type Object:

getValue() returns the data contained in this snapshot as native types. The possible types returned are:

  • Boolean
  • String
  • Long
  • Double
  • Map<String, Object>
  • List

由于 Firebase 实时数据库中的每个节点都可以由成对的键和值表示,实际上是地图,您必须使用该转换才能真正读取数据。

或者,您可以使用 DataSnapshot#getValue(Class valueType) 将每个节点映射到特定 class 的对象。

编辑:

I studied that getValue() is just an object so can you tell me of which class it's an object?

getValue() returns 类型 Object 的对象。对象 class 是所有 class 继承自的 class。

and one more thing if we know some class's object can return a String, Boolean, Map, etc. then every time we need to cast its return type.

是的,你必须转换为相应的值。

Like in my case I wanna use a map so I cast it to hashmap okay...but if I want to have string value from getValue() then I need to cast it as String right?.

是的,确实,这就是你必须要做的。或者您可以使用替代解决方案。

当在包含多个值的 DataSnapshot 上调用时,getValue() returns 一个 Map<String,Object> 因为(根据定义键是字符串)它不知道您数据库中的所有值都是什么类型。

如果您 知道 所有值都是字符串,您可以像这样做一样将结果转换为 Map<String,String>,但它确实需要您转换结果从 getValue().

回来