Why is Scala Map automatically imported but no HashMap?

If we use a card, you do not need to import an immutable card

scala> val map=Map[String,Int]()
map: scala.collection.immutable.Map[String,Int] = Map()

But if we use HashMap, then without import, it gives an error.

scala> val a=HashMap[Int,Int]()
 <console>:7: error: not found: value HashMap
       val a=HashMap[Int,Int]()
             ^

but making scala.collection.immutable.HashMap import, it works.

I also see it with Set and Hashset ..

I notice that Map and Set are traits, and HashSet, HashMap are classes.

So why is this so ???

EDIT

The Stack and Queue classes also exist in the scala.collection package. then why do we need to import these classes. ???

+5
source share
4 answers

The program is for the interface, not for implementation . Scala designers encouraged this by providing shortcuts to interfaces in Predef.

+14

, Predef . factory , Map. HashMap , , factory , .

+3

Scala , , . , .

Another potential reason (and I just guess) is that a HashMap is a map, and in many cases you don't care what specific Map implementation you get, you just need something that can associate keys with values ​​and have fast enough search. So it's more abstract to just say Map ("foo" → "bar") than HasArrayMappedTrie ("foo" → "bar").

+1
source

This is likely due to the hierarchy of this collection class:

enter image description here

0
source

All Articles