我不明白为什么两段代码要做完全相同的事情,在Scala中做不同的事情。
第一个例子:
scala> val ggg = Source.fromFile("/somefile");
ggg: scala.io.BufferedSource = non-empty iterator
scala> ggg.getLines();
res67: Iterator[String] = empty iterator第二个例子:
scala> Source.fromFile("/somefile").getLines();
res68: Iterator[String] = non-empty iterator他们不是要做同样的事情吗,还是我错过了什么?
发布于 2011-08-10 23:14:41
这似乎是个怪癖(bug?)用BufferedSource.toString。观察:
// no problem
scala> { val x = Source.fromFile("foo.txt"); x.getLines() }
res10: Iterator[String] = non-empty iterator
// ahh, calling toString somehow emptied our iterator
scala> { val x = Source.fromFile("foo.txt"); println(x.toString); x.getLines() }
non-empty iterator
res11: Iterator[String] = empty iterator为了显示表达式的值,REPL需要调用BufferedSource.toString,这有清空迭代器的副作用。
发布于 2011-08-10 23:34:39
https://stackoverflow.com/questions/7018893
复制相似问题