score:2

Accepted answer

Try changing the return type of getFileNames toList[String] and use map(_.getName) like so

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
    }
  }

Make sure .map(_.getName) is the last in the chain, that is, after sortBy.

better-files would simplify this to

import better.files._
import better.files.Dsl._
val file = file"."
ls(file).toList.filter(_.isRegularFile).map(_.name)

score:1

you can use getName method

and as Tomasz pointed out, filter and map can be combined to collect as following

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
  }
}

Related Query

More Query from same tag