4

I have the following two Maps in the REPL in Scala:

Case 1

scala> var a1=Map("a" -> "b", "c" -> "d", "e" -> "f", "g" -> "h") 
a1: scala.collection.immutable.Map[String,String] = Map(a -> b, c -> d, e -> f, g -> h)

scala> var a2=Map("a" -> "b","c" -> "d","e" -> "f","g" -> "h","i" -> "j")
a2: scala.collection.immutable.Map[String,String] = Map(e -> f, a -> b, i -> j, g -> h, c -> d)

Both of the above examples print the same text in the REPL:

...
scala.collection.immutable.Map[String,String] = ...

But the following two examples show different output text:

Case 2

scala> a1.getClass.getName
res10: String = scala.collection.immutable.Map$Map4

scala> a2.getClass.getName
res11: String = scala.collection.immutable.HashMap$HashTrieMap

Why are the text outputs (scala.collection.immutable.Map$Map4 and scala.collection.immutable.HashMap$HashTrieMap) in the REPL different? What does the output text mean exactly? I know that Map with more than four elements uses HashMap instead of Map, but why are the output texts the same in case 1 (for variable a1 and a2), and different in case 2?

Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54
Andrew_256
  • 229
  • 2
  • 6
  • 1
    For performance reasons, `Map.apply` (which is called implicitly) returns a different implementation of the `Map` trait, depending of how many key-value pairs are stored. – jub0bs Apr 17 '18 at 15:01

1 Answers1

3

If you have a look in the reference documentation, you can read that a HashTrieMap is the default implementation of an immutable map.

However, Scala has a further optimization for immutable sets and maps that contain less than five elements. Sets and maps with one to four elements are stored as single objects that just contain the elements (or key/value pairs in the case of a map) as fields - that is why you see the class Map4.

themathmagician
  • 467
  • 5
  • 16
  • Maps don't typically guarentee iteration order. If you need an immutable map that does then [ListMap](https://www.scala-lang.org/api/current/scala/collection/immutable/ListMap.html) is what you want. – ggovan Apr 17 '18 at 17:10
  • Ok, thanks. I understand the performance reason but why are not the output texts different in case 1? Why does the case 1 contain the following text `scala.collection.immutable.Map[String,String]` and not `...scala.collection.immutable.Map$Map4...` or `...scala.collection.immutable.HashMap$HashTrieMap...`? – Andrew_256 Apr 17 '18 at 19:05
  • `scala.collection.immutable.Map[String,String]` is the type of the variable `a1`, `Map4` is the type of the value held by `a1` – ggovan Apr 18 '18 at 08:16