简体   繁体   中英

Scala REPL not printing Range

When I try to print a Range in Scala REPL, how come it doesn't give me the list of numbers.

It displays Range(0 to 10) instead of printing Range(1,2,3,4,5,6,7,8,9,10) .

Scala REPL range printout

It looks like the toString function for Range has changed in Scala 2.12 .

Testing with 2.12.0 :

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

Testing with 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)
}

An easy solution, when you're lost with the bounds of your Range and want to inspect its actual individual elements, consists in transforming it as a 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM