Scala REPL不打印Range

时间:2017-03-10 02:21:30

标签: scala range read-eval-print-loop

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

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

Scala REPL range printout

2 个答案:

答案 0 :(得分:6)

看起来,在Scala toString中,Range的2.12函数已更改。

使用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)
}

答案 1 :(得分:0)

一个简单的解决方案是,当您迷失了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)