I need to simply count lines of Scala code in a project, which includes some package(i.e. directory) hierarchy.
I'm not sure about the performance of the code below. Can you help improve it, if possible?
Also, in Java, we have reduce() in the Stream API, and I didn't find its counterpart in the Scala library, so ended with foldLeft().
import java.io.File
import scala.io.Source
object CountLoc {
def main(args: Array[String]): Unit = {
val parentDir: File = new File(System.getProperty("user.dir"))
def traverse(dir: File): Int = {
val all = dir.list().map(f => new File(dir.getAbsolutePath + "/" + f))
val srcs = all.filter(!_.isDirectory).filter(_.getName.endsWith(".scala"))
val dirs = all.filter(_.isDirectory)
srcs.foldLeft(0)((i, f) => i + Source.fromFile(f).getLines().filterNot(_.isEmpty).toList.size) +
dirs.toList.foldLeft(0)((i,d) => i + traverse(d))
}
println("LOC: " + traverse(parentDir))
}
}