实际上是一个愚蠢的情况。有一个处理:
private fun parse(json: JsonObject): HashMap<String, Probe> {
return json.keySet()
.filter { json.get(it).isJsonObject }
.map { it -> Pair(it, json.getAsJsonObject(it)) }
.map {
if (hasInner(it.second))
parse(it.second.getAsJsonObject("snapshot_groupSnapshotChildren"))
else
hashMapOf(it.first to probe(it.second))
}.flatMap { it.toList() }
.toMap() as HashMap<String, Probe>
}
在其中一次迭代中,返回一个空的Map
,据我所知,它被转换为一个安静的EmptyMap
,不能被转换为HashMap
. 我怎样才能说服他我需要空着HashMap
而不是返回EmptyMap
?
UPD调查了来源toMap
......
public fun <K, V> Iterable<Pair<K, V>>.toMap(): Map<K, V> {
if (this is Collection) {
return when (size) {
0 -> emptyMap()
1 -> mapOf(if (this is List) this[0] else iterator().next())
else -> toMap(LinkedHashMap<K, V>(mapCapacity(size)))
}
}
return toMap(LinkedHashMap<K, V>()).optimizeReadOnlyMap()
}
PS 由于 JSON 是递归的并且您需要保存密钥,因此存在这样的困难
有一种方法
Iterable<Pair<K, V>>.toMap(destination: M)
,它的参数是MutableMap
要填充的。