[英]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.