[英]Return type is different when invoking the same method on different objects
我编写了以下应用程序:
var counters: mutable.Map[String, mutable.Map[String, Long]] = mutable.Map()
counters("key1") = mutable.Map("counters_key"→ 20)
counters("key2") = mutable.Map("counters_key" → 920)
counters("key3") = mutable.Map("counters_key" → 920)
counters("key4") = mutable.Map("counters_key" → 920)
counters("key5") = mutable.Map("counters_key" → 920)
var counters2: mutable.Map[String, mutable.Map[String, Long]] = mutable.Map()
counters2("key1") = mutable.Map("counters2_key_1"→ 112000, "counters_key_2" → 1112000, "counters_key_3"→ 20)
counters2("key2") = mutable.Map("counters2_key_4" → 9112000, "counters_key_5" → 91112000, "counters_key_6" → 920)
val flattenedCounters = counters.toMap.values.flatten
val flattenedCounters2 = counters2.toMap.values.flatten
println(flattenedCounters.getClass == flattenedCounters2.getClass)
//true
println(flattenedCounters.groupBy(_._1).getClass ==
flattenedCounters2.groupBy(_._1).getClass)
//false
我们正在相同类型的2个对象上调用相同的方法。 但这给了我们不同类型的对象。 为什么?
关键在于柜台的大小
val map = counters.toMap
println(map.getClass)
//class scala.collection.immutable.HashMap$HashTrieMap
println(map.size)
//5
val map2 = counters2.toMap
println(map2.getClass)
//class scala.collection.immutable.Map$Map2
println(map2.size)
//2
看起来Scala有一些Map
实现。 Map2
经过优化,可精确容纳2个元素。 并且有多达Map4
优化实现
您可以在源代码中找到这些类
调用toMap
它会创建一个包含空地图的新生toMap
。 然后为每个元素将其添加到地图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.