为什么相同的对象在IntelliJ Scala REPL中获得不同的打印输出,具体取决于它们的创建方式?

时间:2016-07-15 17:00:29

标签: scala intellij-idea

这是我今天在使用IntelliJ中的Scala REPL时注意到的有趣内容。

鉴于这两行:

val myVector = Vector.tabulate(10)((x: Int) => x + 1)
val myVector2 = (1 to 10).toVector

REPL打印:

myVector: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
myVector2: Vector[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

为什么第一个显示整个路径(scala.collection.immutable.Vector [Int]),而第二个只显示Vector [Int]?

为了涵盖所有基础,我确认他们确实是同一个班级:

myVector: Class[?0] = class scala.collection.immutable.Vector
myVector2: Class[?0] = class scala.collection.immutable.Vector

这更像是一种好奇心,但对于最有可能使用REPL的初学者来说,这可能会让人感到困惑。

1 个答案:

答案 0 :(得分:2)

您可以获得详细类型信息:

$ scalam 
Welcome to Scala 2.12.0-M5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_92).
Type in expressions for evaluation. Or try :help.

scala> :type -v Vector.tabulate(10)((x: Int) => x + 1)
// Type signature
scala.collection.immutable.Vector[Int]

// Internal Type structure
TypeRef(
  TypeSymbol(
    final class Vector[+A] extends AbstractSeq[A] with IndexedSeq[A] with GenericTraversableTemplate[A,scala.collection.immutable.Vector] with IndexedSeqLike[A,scala.collection.immutable.Vector[A]] with VectorPointer[A @scala.annotation.unchecked.uncheckedVariance] with Serializable with CustomParallelizable[A,scala.collection.parallel.immutable.ParVector[A]]

  )
  args = List(
    TypeRef(TypeSymbol(final abstract class Int extends AnyVal))
  )
)

scala> :type -v (1 to 10).toVector
// Type signature
Vector[Int]

// Internal Type structure
AliasTypeRef(
  Alias(type Vector[+A] = scala.collection.immutable.Vector[A])
  args = List(
    TypeRef(TypeSymbol(final abstract class Int extends AnyVal))
  )
  normalize = TypeRef(
    TypeSymbol(
      final class Vector[+A] extends AbstractSeq[A] with IndexedSeq[A] with GenericTraversableTemplate[A,scala.collection.immutable.Vector] with IndexedSeqLike[A,scala.collection.immutable.Vector[A]] with VectorPointer[A @scala.annotation.unchecked.uncheckedVariance] with Serializable with CustomParallelizable[A,scala.collection.parallel.immutable.ParVector[A]]

    )
    args = List(
      TypeRef(TypeSymbol(final abstract class Int extends AnyVal))
    )
  )
)

你可能会像我一样说,“什么?”

TraversableOnce.toVector中有类型scala.Vector

 def toVector: Vector[A] = to[Vector]

tabulate工厂方法在GenTraversableFactory上,所以我不会去那里。但显然返回类型可能是一个类型arg,因为没有结果的Vector而摇摆不定。

应该补充说,他们正在考虑自定义打印值和类型。并且有一个comment on the :type command来添加一个选项来规范化类型以避免这个问题。

此外,这是一个很好的:

scala> Vector
res0: collection.immutable.Vector.type = scala.collection.immutable.Vector$@5ffd35dd