Kotlin Map of Map 中的括号符号

Bracket notation in a Map of Map in Kotlin

在 Kotlin 中,可以对 Map 使用括号表示法,因此以下代码:

  val mapOfMap: Map<String, Map<String, String>> = mapOf("Key1" to mapOf("Subkey1" to "Value1", "Subkey2" to "Value2"))
  println(mapOfMap["Key1"])

打印:

{Subkey1=Value1, Subkey2=Value2}

太好了。但为什么我不能执行以下操作

println(mapOfMap["Key1"]["Subkey1"])

它会导致编译错误:Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Map?

处理这个问题的正确方法是什么?

因为 mapOfMap["Key1"] 可能 return 为空,因为它无法猜测所需的键是否在映射中。和调用mapOfMap.get("Key1")一样。第二个映射可以为空,因此它不能在其上调用另一个 .get()。您可以这样做:mapOfMap["Key1"]?.get("Subkey1")

mapOfMap["Key1"] returns Map<String, String>?get 运算符未指定为可空 Map。因此,以下代码无法编译:

mapOfMap["Key1"]["Subkey1"]

您可以通过创建扩展 get operator 具有可为空 Map 接收者的函数使其编译:

operator fun <K, V> Map<K, V>?.get(key: K): V? = this?.get(key)

您还可以为地图的地图创建扩展 get operator 函数:

operator fun <K1, K2, V> Map<K1, Map<K2, V>>.get(key1: K1, key2: K2): V? = get(key1)?.get(key2)

并这样使用:

mapOfMap["Key1", "Subkey1"]