Tom K Tom K - 10 months ago 56
Scala Question

Scala and case classes

I am reading in a file, and appending line numbers to each file. Below is a List to facilitate this example:

val testList: List[String] = List("Dont", "Do", "It"

val output: List[(String, Int)] = (testList.zipWithIndex)

My program is getting a bit of code-smell with using the ._1 & ._2 accessors. I created:

case class File(line: String, lineNum: Int)

However, the only way I know how to make best use of this case class would be to use the following:

val fileOutput: List[File] = for{(line, lineNum) <- output} yield{File(line, lineNum)}

My question: why can't I do this?

val output: List[File] = (testList.zipWithIndex)

I'm a bit weary of doing two passes on my file for the sake of using a case-class.

Thanks in advance

Answer Source

If you use Iterators you can avoid multiple passes (because they are lazy), e.g.

for ((line, lineNum) <- testList.iterator.zipWithIndex) yield File(line, lineNum)