【问题标题】:Scala 'fromFile' weirdness?Scala'fromFile'怪异?
【发布时间】:2011-08-11 07:34:39
【问题描述】:

我不明白为什么要执行完全相同的事情的两段代码在 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

他们不是打算做同样的事情,还是我错过了什么?

【问题讨论】:

  • 您不需要分号。它在 REPL (2.8.2.RC1) 中对我有用。

标签: scala io


【解决方案1】:

这似乎是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,这有清空迭代器的副作用。

【讨论】:

【解决方案2】:

看起来像这个错误:SI-4662

显然已在主干Changeset 25212 中修复,但据我所知,在 2.9.1 中未修复。

在错误说明中提到它可能仅在 REPL 中出现,而不是在“真实”代码中。

【讨论】:

    猜你喜欢
    • 2012-10-28
    • 2014-09-17
    • 2010-10-12
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多