I prefer something like this:
def traverse(root: File): Iterator[File] =
if (root.isDirectory)
root.listFiles.iterator.map(traverse).fold(Seq(root).iterator)(_ ++ _)
else
Seq(root).iterator
You can use that iterator with a foreach
(as you are doing), but you get a lot more of flexibility, you can do map
, filter
, and all the usual Scala awesomeness very easily. For example, this is what you were doing
def whatever(root:File, proc:File => Unit) = traverse(root) foreach proc
There may be more efficient (@tailrec
maybe), lazy or better options. I'd be interested in seeing them, this was just the most immediate solution I could think of to put an example.
PD: this doesn't filter the files that are directories, you can impose that constraint with something of the form:
def traverse(root: File): Iterator[File] =
if (root.isDirectory)
root.listFiles.iterator map traverse reduce (_ ++ _)
else
Seq(root).iterator
But I'd suggest not to do that.
PD: perhaps the signature should be something like:
def toTraversable(root:File): Traversable[File]
Maybe its in the standard Scala API already...