Scala: How to list files and directories under a directory

When using Scala, if you ever need to list the subdirectories in a directory, or the files under a directory, I hope this example is helpful:


object FileTests extends App {

    // list only the folders directly under this directory (does not recurse)
    val folders: Array[File] = (new File("/Users/al"))
        .filter(_.isDirectory)  //isFile to find files


If it helps to see it, a longer version of that solution looks like this:

val file = new File("/Users/al")
val files = file.listFiles()
val dirs = files.filter(_.isDirectory)

As noted in the comment, this code only lists the directories under the given directory; it does not recurse into those directories to find more subdirectories. Also as noted, use isFile to check to see if the “files” are files and isDirectory to see if the files are really directories.