Scala REPL 不打印范围

Scala REPL not printing Range

当我尝试在 Scala REPL 中打印 Range 时,为什么它没有给我数字列表。

它显示 Range(0 to 10) 而不是打印 Range(1,2,3,4,5,6,7,8,9,10)

Scala REPL range printout

在 Scala 2.12 中,Range 的 toString 函数似乎发生了变化。

使用 2.12.0 进行测试:

scala> (1 to 10)
res0: scala.collection.immutable.Range.Inclusive = Range 1 to 10

使用 2.11.8 进行测试:

scala> (0 to 10)
res0: scala.collection.immutable.Range.Inclusive = Range(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

Source code for 2.12:

override def toString = {
  val preposition = if (isInclusive) "to" else "until"
  val stepped = if (step == 1) "" else s" by $step"
  val prefix = if (isEmpty) "empty " else if (!isExact) "inexact " else ""
  s"${prefix}Range $start $preposition $end$stepped"
}

Source code for 2.11:

override def toString() = {
  val endStr =
    if (numRangeElements > Range.MAX_PRINT || (!isEmpty && numRangeElements < 0)) ", ... )" else ")"
    take(Range.MAX_PRINT).mkString("Range(", ", ", endStr)
}

如果您迷失了 Range 的边界并想检查其实际的单个元素,一个简单的解决方案是将其转换为 List:

scala> (0 until 10)
res0: scala.collection.immutable.Range = Range 0 until 10
scala> (0 until 10).toList
res1: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)