从 scala 中的 stdio 读取时的 val 评估

val evaluation while reading from stdio in scala

这个程序从 std io 中读取一些数字(每个数字占一行)。我只输入一次数字! 现在,值 "it" 应该在定义点进行评估(与惰性 val 相反)并且 "it" 应该被 RHS 的结果替换。

因此,在调用第一个 println(it.size) 时,"it" 已经求值了。那为什么第二次调用 prinln 总是 return 为零?似乎它试图再次从 std io 读取,但由于没有读取任何内容,它 return 为零。

object Test {
    def main(args: Array[String]) {
        val it= io.Source.stdin.getLines().map(_.toInt)
        println(it.size) // prints correct number of lines
        println(it.size) // prints zero always????   
    }
}

Then why does the second call to prinln always return zero

因为 Source.getLines returns an Iterator[String], which you're iterating completely with the invocation of it.size, which means the iterator reached it's end. This is how size is defined on TraversableOnce[A]Iterator[A] 扩展):

def size: Int = {
  var result = 0
  for (x <- self) result += 1
    result
}

如果你想多次迭代,你需要先实现迭代器:

def main(args: Array[String]): Unit = {
  val it = io.Source.stdin.getLines().map(_.toInt).toSeq
  println(it.size)
  println(it.size)
}

请注意,此具体化会导致将整个迭代器加载到内存中。