Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala getLines() with yield not as I expect

Tags:

scala

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.

like image 358
Jay Daley Avatar asked Dec 09 '22 06:12

Jay Daley


2 Answers

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].

like image 61
huynhjl Avatar answered Dec 11 '22 18:12

huynhjl


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
like image 34
dhg Avatar answered Dec 11 '22 20:12

dhg