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