Why does Scala immutable HashMap methods return a map?

I'm having problems using the scala.collection.immutable.HashMap.I update method. I don’t see the reason why it returns the map instead of the HashMap. How can I get a new HashMap with a new key-value pair added?

+4
source share
3 answers

This is the expected behavior. HashMap most useful as a concrete implementation of Map , including the use of a hash table for searching.

You can usually say var values: Map[String, Any] = new HashMap , and then lean back and use it as if it were a simple and immutable Map .

Do you have a reason why your code knows that it is a HashMap after you new it as above?

+7
source

If you use 2.7, this is due to the fact that over time the collection library has become incompatible with a different implementation class that does not specialize in the return types of some methods. This is one of the things that has been fixed in the redesign of the collection library for 2.8.

If you are using 2.8, this is because the update method is deprecated and you should use updated instead. This sets the return value correctly.

 scala> HashMap(1->1, 2->2, 3->3, 4->4).updated(1,3) res4: scala.collection.immutable.HashMap[Int,Int] = Map((2,2), (4,4), (1,3), (3,3)) 
+7
source

In 2.7.x, it returns a Map because it could be a ListMap or TreeMap or something else, and it was considered that it was too much work to redefine the methods every time.

In 2.8.x, it should return a HashMap - but you should use updated ( update deprecated).

+2
source

Source: https://habr.com/ru/post/1306630/


All Articles