A Scala function to list subdirectories in a directory

If you ever need to generate a list of subdirectories in a directory in Scala, here’s one way to do it:

def getListOfSubDirectories(directoryName: String): Array[String] = {
    (new File(directoryName))

I intentionally wrote that function in a short, “Scala like” style, but you can expand it to multiple lines by using intermediate variables, if you prefer.

To demonstrate the use of this directory-listing function, you can print all your subdirectories like this:

def main(args: Array[String]) {

How to get a list of subdirectories, the Java way

As a contrast, here’s how you’d get a list of subdirectories in Scala if you were programming in a “Java style”:

 * Get a List[String] representing all the sub-directories in the given directory.
def getListOfSubDirectoriesJavaStyle(directoryName: String): List[String] = {
    val directory = new File(directoryName)
    val files = directory.listFiles  // this is File[]
    val dirNames = ArrayBuffer[String]()
    for (file <- files) {
        if (file.isDirectory()) {
            dirNames += file.getName()
    return dirNames.toList

As you can see, there’s a pretty stark contrast in the two versions of the code. If the Scala code is a little too cryptic for you, it doesn’t have to be that short, but I’m comfortable with this style now, so it’s okay for me. It also helps to demonstrate a few differences between a functional style of programming and an imperative style.



Hi Alvin: Thanks for all your blog post (I used them all the time).
On the function getListOfSubDirectories, you do not need "return", and can be deleted.

Hi Guillermo,

Thanks for letting me know. I wrote post this a long time ago when I was first learning Scala. I removed the return in the Scala example, and left it in for the Java one.