How do I list all files in a subdirectory in scala?

后端 未结 19 1439
旧巷少年郎
旧巷少年郎 2020-11-28 03:35

Is there a good \"scala-esque\" (I guess I mean functional) way of recursively listing files in a directory? What about matching a particular pattern?

For example re

相关标签:
19条回答
  • 2020-11-28 04:22

    I personally like the elegancy and simplicity of @Rex Kerr's proposed solution. But here is what a tail recursive version might look like:

    def listFiles(file: File): List[File] = {
      @tailrec
      def listFiles(files: List[File], result: List[File]): List[File] = files match {
        case Nil => result
        case head :: tail if head.isDirectory =>
          listFiles(Option(head.listFiles).map(_.toList ::: tail).getOrElse(tail), result)
        case head :: tail if head.isFile =>
          listFiles(tail, head :: result)
      }
      listFiles(List(file), Nil)
    }
    
    0 讨论(0)
提交回复
热议问题