2 回答

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超16個(gè)贊
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)是鏈中的最后一個(gè),即在 之后sortBy。
更好的文件會(huì)將其簡(jiǎn)化為
import better.files._
import better.files.Dsl._
val file = file"."
ls(file).toList.filter(_.isRegularFile).map(_.name)

TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊
你可以使用 getName 方法
正如 Tomasz 指出的那樣,過(guò)濾器和地圖可以組合起來(lái)收集如下
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 } }
添加回答
舉報(bào)