pau.estalella
pau.estalella

Reputation: 2243

Why do Scala immutable HashMap methods return a Map?

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?

Upvotes: 4

Views: 2103

Answers (3)

Ben Lings
Ben Lings

Reputation: 29403

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))

Upvotes: 7

Rex Kerr
Rex Kerr

Reputation: 167871

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).

Upvotes: 2

sblom
sblom

Reputation: 27343

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?

Upvotes: 7

Related Questions