Scala getLines () with output not as I expect

My understanding of Scala Programming is that the following should return Array[String] , and instead return Iterator[String] . What am I missing?

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

I am using Scala 2.9.
Thanks in advance.

+4
source share
3 answers

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

 for (x <- expr_1) yield expr_2 

translates to

 expr_1.map(x => expr_2) 

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

+12
source

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

But the following should work if your goal is Array :

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

If you want to convert Iterator to Array (as indicated in your comment), try the following after you get your Iterator :

 data.toArray 
+2
source

@dhg is true, and here is a little more detail on why.

The code in your example makes calls to Source.fromFile, which returns a BufferedSource. Then you call getLines, which returns an iterator. This iterator is then output and stored as data.

Calling toArray on an Iterator will give you an array of strings as you want.

0
source

All Articles