Bajro Bajro - 1 year ago 101
Scala Question

Scala foldLeft with a List

I have the following code snippet:

object test extends App {

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

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

fileContent foreach println


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download