Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Scala Map auto-imported but HashMap isn't?

If we use map then no need to import immutable map

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

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

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

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

I also see it with Set and Hashset..

I notice one thing that Map and Set are trait and HashSet,HashMap are classes.

So Why it is so ???

EDIT

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

like image 970
Rishi Avatar asked Feb 12 '13 16:02

Rishi


3 Answers

Program to an interface, not an implementation. Scala designers encouraged this by providing shortcuts to interfaces in Predef.

like image 129
om-nom-nom Avatar answered Sep 21 '22 22:09

om-nom-nom


It's because Predef is implicitly imported. Among others, it contains factory methods for common traits like Map. HashMap is a a concrete implementation, so if you used its factory method with type inference, you would tightly couple your declaration to an implementation.

like image 44
thSoft Avatar answered Sep 23 '22 22:09

thSoft


In Scala, it's idiomatic to prefer immutable types, so those are made available by default. If you want mutation you have to explicitly say so.

Another potential reason (and I'm just guessing) is that HashMap is a Map, and in many cases you don't really care what concrete implementation of Map you get, you just want something that can associate keys with values and have reasonably fast lookups. So it's more abstract to just say Map("foo" -> "bar") than HasArrayMappedTrie("foo" -> "bar").

like image 23
overthink Avatar answered Sep 20 '22 22:09

overthink