使用getClass 获取对象的运行时类。其余答案扩展了 Luis 的评论。
Scala 2.13.2 为Vector 引入了implementation subclasses
第二个主要区别在于实现。而老
Vector 对所有支持大小的集合使用单个类,即
新的被分成Vector0 到Vector6 用于不同的尺寸
的主数据数组。 Vector0 是空的单例对象
向量,Vector1(用于大小不超过 32 的集合)本质上是
和ArraySeq一样,所有更高的维度都是手指树。
/* Contents of Vector.scala in 2.13.2 */
object Vector extends StrictOptimizedSeqFactory[Vector]
sealed abstract class Vector[+A] ...
private sealed abstract class VectorImpl[+A](...) extends Vector[A]
private sealed abstract class BigVector[+A](...) extends VectorImpl[A]
private object Vector0 extends BigVector[Nothing]
private final class Vector1[+A](...) extends VectorImpl[A]
private final class Vector2[+A](...) extends BigVector[A]
private final class Vector3[+A](...) extends BigVector[A]
private final class Vector4[+A](...) extends BigVector[A]
private final class Vector5[+A](...) extends BigVector[A]
private final class Vector6[+A](...) extends BigVector[A]
...
Scala 中不存在的 2.13.1
/* Contents of Vector.scala in 2.13.1 */
object Vector extends StrictOptimizedSeqFactory[Vector]
final class Vector[+A] ...
...
因此Vector(1)在2.13.2中的运行时类是Vector1
Welcome to Scala 2.13.2 (OpenJDK 64-Bit Server VM, Java 1.8.0_202).
Type in expressions for evaluation. Or try :help.
scala> Vector(1).getClass.getCanonicalName
val res0: String = scala.collection.immutable.Vector1
而 Vector(1) 在 2.13.1 中的运行时类是 Vector
Welcome to Scala 2.13.1 (OpenJDK 64-Bit Server VM, Java 1.8.0_202).
Type in expressions for evaluation. Or try :help.
scala> Vector(1).getClass.getCanonicalName
res0: String = scala.collection.immutable.Vector
从概念上讲,Scala 集合区分 concrete collection type and implementation subclasses
/** Defines the prefix of this object's `toString` representation.
*
* It is recommended to return the name of the concrete collection type, but
* not implementation subclasses. For example, for `ListMap` this method should
* return `"ListMap"`, not `"Map"` (the supertype) or `"Node"` (an implementation
* subclass).
*
* The default implementation returns "Iterable". It is overridden for the basic
* collection kinds "Seq", "IndexedSeq", "LinearSeq", "Buffer", "Set", "Map",
* "SortedSet", "SortedMap" and "View".
*
* @return a string representation which starts the result of `toString`
* applied to this $coll. By default the string prefix is the
* simple name of the collection class $coll.
*/
protected[this] def className: String = stringPrefix
例如,我们将Vector1 称为实现子类,而将Vector 称为concrete collection class,尽管Vector 从技术上讲是一个抽象类。
我们也可以观察其他集合类型的实现子类,例如
scala> Set(1).getClass.getCanonicalName
val res1: String = scala.collection.immutable.Set.Set1
实现子类通常是private implementation detail:
您从 Map(...) 或 toMap 获得的具体运行时类是
实施细节和绝大多数时候你不应该
需要担心(但当你这样做时,你可以与getClass联系)。