问题
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.
回答1:
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
).
来源:https://stackoverflow.com/questions/37381096/what-is-the-actual-class-not-abstract-and-not-trait-for-map-and-set