Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the Scala interpreter (REPL) print exactly (demonstration with Map and HashMap)?

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?

like image 233
Andrew_256 Avatar asked Nov 05 '25 19:11

Andrew_256


1 Answers

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.

like image 86
themathmagician Avatar answered Nov 08 '25 13:11

themathmagician