0

Is there a reason for a SortedMap with a default value becoming a regular unsorted 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)
Roberto Bonvallet
  • 31,943
  • 5
  • 40
  • 57

1 Answers1

6

The function withDefaultValue is implemented in Map and returns a wrapper type WithDefault that has the original Map as an underlying implementation.

Although the type is just Map[A, B], the underlying map is still your sorted map. Keys you add will still be sorted:

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))
Sascha Kolberg
  • 7,092
  • 1
  • 31
  • 37
  • Thanks for the explanation. I managed to create an example that proves that the underlying map is still sorted, even when the same keys appear in a different order in a regular map, so I believe you :) – Roberto Bonvallet Sep 14 '15 at 15:03