[英]scala mutable Map withDefaultValue strange behaviour
我有一個使用可變HashMap.withDefaultValue
示例。 withDefaultValues
提供了一種即使鍵不存在也可以返回值的方法,但是該鍵不應修改集合。 無論如何,都會有沖突的行為,因為map.size
返回0,同時map(key)
返回一個值。
這怎么可能?
import scala.collection.mutable
val map = mutable.HashMap[String, mutable.Map[Int, String]]()
.withDefaultValue(mutable.HashMap[Int, String]())
map("id1")(2) = "three"
println(map.size) // 0 (expected)
println(map) // Map() (expected)
println(map("id1")) // Map(2 -> three) (unexpected)
println(map("id1")(2)) // three (unexpected)
可以將defaultValue
排除在外,因為它是作為值傳遞的。
import scala.collection.mutable
val defaultValue = mutable.HashMap[Int, String]()
val map = mutable.HashMap[String, mutable.Map[Int, String]]()
.withDefaultValue(defaultValue)
map("id1")(2) = "three"
這給你
println(defaultValue) // Map(2 -> three)
...這應該解釋其余的行為。 這就是為什么我推薦不可變數據結構的原因;-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.