views:

391

answers:

4

Hi all!

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

+5  A: 

That's the expected behavior. HashMap is most useful as a specific implementation of Map involving using a hash table for lookups.

Usually, you'd say var values: Map[String, Any] = new HashMap, and then sit back and use it as if it's a plain ol' immutable Map.

Do you have a reason for your code to know that it's a HashMap after you've new'd it as above?

sblom
Aaaaaah, I see. Finally I got my code working! Thanks!
pau.estalella
Glad I could help.
sblom
+6  A: 

If you're using 2.7 this is because over time the collections library has become inconsistent with various implementation class not specializing the return types of some methods. This is one of the things that is fixed in the collections library redesign for 2.8.

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

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))
Ben Lings
+2  A: 

In 2.7.x, it returns a Map because it might be a ListMap or TreeMap or whatever, and it was deemed to be too much work to redefine the methods each time.

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

Rex Kerr
A: 

According to the 2.8 language specification, 6.15 Assignments: Something like (m,v) => m(v) = v.length translates to m.update(v, v.length), which is a useful syntax for adding to maps. By deprecating update for HashMaps features like these now spit out deprecation warnings - shouldn't this have all been changed at once?

Simon Beverton