Jay Daley
Jay Daley

Reputation: 286

Scala getLines() with yield not as I expect

My understanding of the "Programming in Scala" book is that the following should return an Array[String] when instead it returns an Iterator[String]. What am I missing?

val data = for (line <- Source.fromFile("data.csv").getLines()) yield line

I'm using Scala 2.9.
Thanks in advance.

Upvotes: 4

Views: 1971

Answers (3)

huynhjl
huynhjl

Reputation: 41646

The chapter you want to read to understand what's happening is http://www.artima.com/pins1ed/for-expressions-revisited.html

for (x <- expr_1) yield expr_2 

is translated to

expr_1.map(x => expr_2)

So if expr_1 is an Iterator[String] as it is in your case, then expr_1.map(line => line) is also an Iterator[String].

Upvotes: 12

David Eagen
David Eagen

Reputation: 782

@dhg is correct and here is a bit more detail on why.

The code in your example calls calls Source.fromFile which returns a BufferedSource. Then you call getLines which returns an iterator. That iterator is then yielded and stored as data.

Calling toArray on the Iterator will get you an array of Strings like you want.

Upvotes: 0

dhg
dhg

Reputation: 52691

Nope, it returns an Iterator. See: http://www.scala-lang.org/api/current/index.html#scala.io.BufferedSource

But the following should work if an Array is your goal:

Source.fromFile("data.csv").getLines().toArray

If you want to convert an Iterator to an Array (as mentioned in your comment), then try the following after you've yielded your Iterator:

data.toArray

Upvotes: 2

Related Questions