Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala 'fromFile' weirdness?

Tags:

io

scala

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?

like image 735
Kristina Brooks Avatar asked Aug 10 '11 22:08

Kristina Brooks


2 Answers

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.

like image 85
Kipton Barros Avatar answered Nov 17 '22 23:11

Kipton Barros


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.

like image 39
Jostein Stuhaug Avatar answered Nov 18 '22 01:11

Jostein Stuhaug