Map和Set的实际类(不是抽象类也不是特征类)是什么? [英] What is the actual class (not abstract and not trait) for Map and Set?
问题描述
在Scala中,可以通过
In Scala, map and set literals can be created through, for instance,
val m = Map(1->"a")
以及引用类型 m
和文字都是 Map [Int,String]
。
And the type of the reference m
and the literal are both Map[Int, String]
.
不过,scala文档显示 Map
实际上是一个特征,需要实例化抽象成员才能实现:
scala.collection.Map
,
< a href = http://www.scala-lang.org/api/2.11.8/#scala.collection.immutable.Map rel = noreferrer> scala.collection.immutable.Map
,
scala.collection.mutable.Map
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
所以我的问题是:什么是文字 Map
所基于的实际的具体类?上面的相同问题同样适用于 Set
。
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.
推荐答案
您可以使用 getClass
找到具体的运行时类:
You can find the concrete runtime class with getClass
:
scala> println(m.getClass)
class scala.collection.immutable.Map$Map1
所以它是 Map1
,这是在 Map
随播对象内定义的类。但是然后我们在稍大的地图上尝试同样的事情:
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
又是另一个类。
简而言之,您所使用的具体运行时类从 Map(...)
或 toMap
获取是实现细节,并且绝大部分时间不应该不必担心(但是这样做时,可以使用 getClass
进行检查)。
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
).
这篇关于Map和Set的实际类(不是抽象类也不是特征类)是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!