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. ???
Program to an interface, not an implementation. Scala designers encouraged this by providing shortcuts to interfaces in Predef.
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.
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").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With