Search code examples
scalafunctional-programmingfoldleft

Scala foldLeft with a List


I have the following code snippet:

import scala.io.Source
object test extends App {

  val lineIterator = Source.fromFile("test1.txt").getLines()


  val fileContent = lineIterator.foldLeft(List[String]())((list, currentLine) => { 
    currentLine :: list
    list
    })


    fileContent foreach println

}

Let's assume the test1.txt file is not empty and has some values in it. So my question about the foldLeft function is, why does this example here return an empty list, and when I remove the list at the end of the foldLeft function it works? Why is it returning an empty list under the value fileContent?


Solution

  • The line currentLine :: list does not mutate the original list. It creates a new list with currentLine prepended, and returns that new list. When this expression is not the last one in your block, it will just be discarded, and the (still) empty list will be returned.

    When you remove the list at the end, you will actually return currentLine :: list.