I want to read a file and store the number of occurrences of each word in a Map, using tail recursion. I came up with the following; it seems to work; does it look like it's right?
def countWordsinFile(reader:java.util.Scanner, wordCounts:Map[String,Int]): Map[String,Int] = {
if (!reader.hasNext()) wordCounts
else {
val word = reader.next()
countWordsinFile(reader, wordCounts + (word -> {wordCounts.getOrElse(word,0)+1}))
}
}
// the function is called with a reader from a .txt file and wordCounts is an empty Map()
Is this tail-recursive? If not, then how can I make it so?