为什么SortedMap的默认值不再排序?

时间:2015-09-14 13:49:45

标签: scala scala-collections

SortedMap是否有理由将默认值变为常规未排序的Map?

scala> val a = scala.collection.immutable.SortedMap(1 -> "uno", 3 -> "tres", 2 -> "dos")
a: scala.collection.immutable.SortedMap[Int,String] = Map(1 -> uno, 2 -> dos, 3 -> tres)

scala> a.withDefaultValue("")
res19: scala.collection.immutable.Map[Int,String] = Map(1 -> uno, 2 -> dos, 3 -> tres)

1 个答案:

答案 0 :(得分:6)

函数withDefaultValueMap中实现,并返回一个包装类型WithDefault,其原始Map作为底层实现。

虽然类型只是Map[A, B],但底层地图仍然是您的有序地图。您添加的密钥仍将排序:

val a: SortedMap[Int, String] = scala.collection.immutable.SortedMap(1 -> "uno", 3 -> "tres", 2 -> "dos")
val b = a.withDefaultValue("")

val c = b + (4 -> "quattro")
val d = c + (0 -> "zero")

val e = d.toList

>> e: List[(Int, String)] = List((0,zero), (1,uno), (2,dos), (3,tres), (4,quattro))