[英]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
. f.getName :: leftFileNames
意味着添加f.getName
到年初leftFileNames
并返回一个新的List
,所以不会加入到leftFileNames
。 so for your example, you need to assign the leftFileNames
after every operation, like: 因此,对于您的示例,您需要在每次操作后分配leftFileNames
,例如:
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: 但是最好不要在Scala中使用mutable变量 ,这会引起副作用 ,您可以为此使用带有reverse
map
,例如:
val leftFileNames = leftFiles.map(_.getName).reverse
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.