20

Is there a difference between a Scala Map and a HashMap? I am using the scala.collection.immutable.HashMap.

ryanyuyu
  • 6,366
  • 10
  • 48
  • 53
jstnchng
  • 2,161
  • 4
  • 18
  • 31
  • 1
    [`HashMap`](http://www.scala-lang.org/api/2.11.5/index.html#scala.collection.immutable.HashMap) is an implementation of [`Map`](http://www.scala-lang.org/api/2.11.5/index.html#scala.collection.immutable.Map). As you can see in their definitions `HashMap` is a class and `Map` is a trait. – Peter Neyens Jul 28 '15 at 19:33
  • 4
    In [_Programming in Scala, 1ed_](http://www.artima.com/pins1ed/collections.html#17.3) (search for "_Default immutable map implementations_") they write that a `HashMap` is the default implementation for a `Map` with 5 elements or more. – Peter Neyens Jul 28 '15 at 19:44

1 Answers1

25

scala.collection.immutable.Map is the interface for immutable maps while scala.collection.immutable.HashMap is a concrete implementation.

Creating with Map() or Map.empty gives a special empty singleton map, with Map(a -> b) with up to 4 pairs yields specialized classes for such small maps, and 5 and upwards gives you scala.collection.immutable.HashMap

Hosam Aly
  • 41,555
  • 36
  • 141
  • 182
johanandren
  • 11,249
  • 1
  • 25
  • 30
  • The author didn't specify scala.collection.immutable.Map or scala.collection.Map in the post. Does scala.collection.Map() also give you the same resulting Map implementations as scala.collection.immutable.Map()? – Andrew Norman Feb 17 '17 at 01:41
  • 1
    `scala.collection.Map.{empty, apply}` just delegates to the corresponding factory methods in the immutable `Map` companion. Note though that if you are explicitly using `scala.collection.Map` in a method signature for example, that will accept mutable maps as well as immutable. The `Map` automagically imported (by Predef) is `immutable.Map`. – johanandren Feb 17 '17 at 08:04