【问题标题】:Scala REPL not printing RangeScala REPL 不打印范围
【发布时间】:2017-03-10 02:21:29
【问题描述】:

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

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

Scala REPL range printout

【问题讨论】:

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


    【解决方案1】:

    看起来 Range 的 toString 函数在 Scala 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)
    }
    

    【讨论】:

    • 但它曾经显示数字,不是吗?那改变了吗?
    • 编辑我的答案以反映问题
    • 是的,它看起来自 2.12 以来已更改。谢谢!!
    【解决方案2】:

    当您迷失 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      • 2016-06-23
      • 2021-03-29
      • 2017-12-23
      • 1970-01-01
      相关资源
      最近更新 更多