class test{
import io.Source
import scala.util._
val pathname = "XXXYYY.csv"
val open = Source.fromFile(pathname).getLines
def addelements(list: List[String]) : List[String] = {
def addElementsRecursion(list: List[String]) : List[String] = {
while(open.hasNext){
val tmpVal = open.next()
val newList = list: tmpVal
addElementsRecursion(newList)
}
println(list)
list
}
addElementsRecursion(list)
}
}
val obj = new test()
val list1 = List()
obj.addelements(list1)
The output is:
List(1, 2)
List(1)
List()
The csv file is just a file with the numbers 1 & 2 in it, and the goal of the program is to iterate through this file and then output the numbers in the file in a list.
My question is, shouldn't the program stop the first time it reaches the list statement after the while loop and therefore the final result should be List(1,2). For some reason the list value is changing at the very end even though the recursive function is not called again.
CodePudding user response:
addelements just returns the value you give it, because addElementsRecursion just returns the value you give it. There is a while and println but neither of these change the value of list so it is returned unchanged. In fact they can't change list because it is a val reference to an immutable object.
It is not entirely clear why this code uses both while and a recursive call; the recursive call should be enough for this logic. Perhaps something like this:
def addelements(list: List[String]) : List[String] = {
def addElementsRecursion(list: List[String]) : List[String] =
if (open.hasNext) {
addElementsRecursion(open.next() : list)
} else {
list.reverse
}
addElementsRecursion(list)
}
This code adds to the front of the list and then reverses the result at the end because it is much more efficient to add an element to the front of a list than to add it to the end, especially for long lists.
