I can't understand why two bits of code that are meant to do exactly the same thing, do different things in Scala.
First example:
scala> val ggg = Source.fromFile("/somefile");
ggg: scala.io.BufferedSource = non-empty iterator
scala> ggg.getLines();
res67: Iterator[String] = empty iterator
Second example:
scala> Source.fromFile("/somefile").getLines();
res68: Iterator[String] = non-empty iterator
Aren't they meant to do the same thing, or am I missing something?
This seems to be a quirk (bug?) with BufferedSource.toString
. Observe:
// 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
To show the value of the expression, the REPL needs to call BufferedSource.toString
, and this has the side effect of emptying the iterator.
Looks like this bug: SI-4662.
Apparently fixed in trunk Changeset 25212, but not in 2.9.1 as far as I can see.
In the bug notes it's mentioned that it probably manifests itself only in the REPL, not in "real" code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With