2 回答

TA贡献1801条经验 获得超16个赞
getFileNames尝试更改to的返回类型并像这样List[String]使用map(_.getName)
def getFileNames(path: String): List[String] = {
val d = new File(path)
if (d.exists && d.isDirectory) {
d
.listFiles // create list of File
.filter(_.isFile)
.toList
.sortBy(_.getAbsolutePath().replaceAll("[^a-zA-Z0-9]",""))
.map(_.getName)
} else {
Nil // return empty list
}
}
确保.map(_.getName)是链中的最后一个,即在 之后sortBy。
更好的文件会将其简化为
import better.files._
import better.files.Dsl._
val file = file"."
ls(file).toList.filter(_.isRegularFile).map(_.name)

TA贡献1995条经验 获得超2个赞
你可以使用 getName 方法
正如 Tomasz 指出的那样,过滤器和地图可以组合起来收集如下
def getFileNames(path: String): List[String] = { val d = new File(path) if (d.exists && d.isDirectory) { d .listFiles // create list of File .collect{ case f if f.isFile => f.getName }// gets the name of the file <-- .toList .sortBy(_.getAbsolutePath().replaceAll("[^a-zA-Z0-9]","")) } else { Nil // return empty list } }
添加回答
举报