Scala: Reading a file line by line into Array of lists

arrays, functional-programming, scala

Solution

You could try something like this:

val myArray = fileLines.filterNot(_.isEmpty).map { line =>
    (line.toList).filter(e => e != ' ')
}.toArray

That will give you an array of list elements. You can remove the `.toArray` at the end if you want a List of Lists.

Problem

I'm reading a file line by line and putting into a list. So, if my file has 10 lines, I have ten lists. Now, while doing this or after doing this, I want to add all the lists into an Array. So, I have an Array of Lists, without using "var", so essentially just 'val'. Here's what I have so far: ``` val fileLines = Source.fromFile(filename).getLines.toList for (line <- fileLines) { if (!line.isEmpty) println((line.toList).filter(e => e != ' ')) } ``` I'm just converting every line into a list and removing blank elements. How do I generate a Array of Lists from this? Array being of type val and not try var.

Original source