简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM