Sun
Sun

Reputation: 3564

Scala list not adding elements

I am doing a sample program: adding a list of file names from a list of files. But I am getting an empty list after adding.

My code is this:

val regex = """(.*\.pdf$)|(.*\.doc$)""".r
val leftPath = "/Users/ravi/Documents/aa"

val leftFiles = recursiveListFiles(new File(leftPath), regex)
var leftFileNames = List[String]()

leftFiles.foreach((f:File) => {/*println(f.getName);*/ f.getName :: leftFileNames})

leftFileNames.foreach(println)

def recursiveListFiles(f: File, r: Regex): Array[File] = {
  val these = f.listFiles
  val good = these.filter(f => r.findFirstIn(f.getName).isDefined)
  good ++ these.filter(_.isDirectory).flatMap(recursiveListFiles(_, r))
}

The last statement is not showing anything in the console.

Upvotes: 0

Views: 43

Answers (1)

chengpohi
chengpohi

Reputation: 14217

f.getName :: leftFileNames means add the f.getName to the beginning of leftFileNames and return a new List, so it will not add into the leftFileNames. so for your example, you need to assign the leftFileNames after every operation, like:

leftFiles.foreach((f:File) => leftFileNames =  f.getName :: leftFileNames)

but it's better not use the mutable variable in Scala, it's will cause the side effect, you can use map with reverse for this, like:

val leftFileNames = leftFiles.map(_.getName).reverse

Upvotes: 1

Related Questions