3

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?

bajro
  • 1,199
  • 3
  • 20
  • 33

3 Answers3

5

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.

marstran
  • 26,413
  • 5
  • 61
  • 67
2

You call foldLeft with some start value (in your case an empty list) and a function, which takes an accumulator and the current value. This function returns the new list then. In your implementation the empty list from the first call will propagate to the end of function execution. This is why you get an empty list as a result.

Please look at this example: https://twitter.github.io/scala_school/collections.html#fold

codejitsu
  • 3,162
  • 2
  • 24
  • 38
0

list is immutable, so it is still empty after currentLine :: list. Thus the code within brackets returns an empty List, which is then folded with the next item, still returning an empty List.

Pascal Soucy
  • 1,317
  • 7
  • 17