Reputation: 337
First of all let me apologize in advance for what is my very first question posted on stack overflow and probably a quite stupid one.
Since a Map in scala is instantiated using the following syntax:
val myMap=Map(1->”value1”,2->”value2”)
I was expecting the Map object from scala.collection.immutable
to provide an apply
method with a signature roughly looking like:
def apply[A,B](entries :(A,B)*):Map[A,B]
Obviously I should be blind, but I can’t find such a method. Where is it defined ?
Furthermore, could someone give me information about the purpose of the Map1
, Map2
, Map3
, Map4
classes defined in the Map
object ? Should they be used by the developer or are they only used internally by the language and/or the compiler ? Are they related somehow to the map instantiation scheme i was asking about above ?
Thanks in advance for your help.
Upvotes: 4
Views: 1727
Reputation: 67848
apply
looks like it is defined on scala.collection.generic.GenMapFactory
, a superclass of scala.collection.immutable.Map
. For some reason, Scaladoc simply ignores this method for 2.9.2. (As Rogach notes, it was there in 2.9.1.)
Map1
…Map4
(together with EmptyMap
, which is private) are simply optimisations. These are defined inside Map.scala and really just hold up to four keys and values directly without any further indirection. If one tries to add to a Map4
, a HashMap
will automatically be created.
You normally do not need to create a Map[1-4]
manually:
scala> Map('a -> 1)
res0: scala.collection.immutable.Map[Symbol,Int] = Map('a -> 1)
scala> res0.isInstanceOf[scala.collection.immutable.Map.Map1[_,_]]
res1: Boolean = true
Upvotes: 6