In Scala, map and set literals can be created through, for instance,
val m = Map(1->"a")
And the type of the reference m
and the literal are both Map[Int, String]
.
However, scala documents show that Map
is actually a trait, with abstract members that need to be implemented in order to instantiate:
scala.collection.Map
,
scala.collection.immutable.Map
,
scala.collection.mutable.Map
So my question is: what is the actual, concrete class that the literal Map
is based on? Same question above is applicable to Set
as well.
Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters. A trait definition looks just like a class definition except that it uses the keyword trait.
In scala, trait is a collection of abstract and non-abstract methods. You can create trait that can have all abstract methods or some abstract and some non-abstract methods. A variable that is declared either by using val or var keyword in a trait get internally implemented in the class that implements the trait.
Traits are like interfaces in Java. But they are more powerful than the interface in Java because in the traits you are allowed to implement the members. Traits can have methods(both abstract and non-abstract), and fields as its members.
You can find the concrete runtime class with getClass
:
scala> println(m.getClass)
class scala.collection.immutable.Map$Map1
So it's Map1
, a class defined inside the Map
companion object. But then we try the same thing on a slightly larger map:
scala> val m2 = Map(1 -> "a", 2 -> "b")
m2: scala.collection.immutable.Map[Int,String] = Map(1 -> a, 2 -> b)
scala> println(m2.getClass)
class scala.collection.immutable.Map$Map2
Which is a different class. Let's try a map with more elements:
scala> println((0 to 10).map(i => i -> i.toString).toMap.getClass)
class scala.collection.immutable.HashMap$HashTrieMap
Which is yet another class.
In short, the concrete runtime class that you get from Map(...)
or toMap
is an implementation detail and the vast majority of the time you shouldn't need to worry about it (but when you do, you can check with getClass
).
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