Wolkenarchitekt
Wolkenarchitekt

Reputation: 21248

Scala method that returns multiple concatenated filter functions

In my app, I'm filtering a file array by various types, like the following:

val files:Array[File] = recursiveListFiles(file)
  .filter(!_.toString.endsWith("png"))
  .filter(!_.toString.endsWith("gif"))
  .filter(!_.toString.endsWith("jpg"))
  .filter(!_.toString.endsWith("jpeg"))
  .filter(!_.toString.endsWith("bmp"))
  .filter(!_.toString.endsWith("db"))

But it would be more neatly to define a method which takes a String array and returns all those filters as a concatenated function. Is that possible? So that I can write

val files:Array[File] = recursiveListFiles(file).filter(
  notEndsWith("png", "gif", "jpg", "jpeg", "bmp", "db") 
)

Upvotes: 8

Views: 565

Answers (2)

Moritz
Moritz

Reputation: 14212

You could do something like this:

def notEndsWith(suffix: String*): File => Boolean = { file =>
  !suffix.exists(file.getName.endsWith)
}

Upvotes: 10

Fabian Steeg
Fabian Steeg

Reputation: 45754

One way would be something like this:

def notEndsWith(files:Array[File], exts:String*) = 
  for(file <- files; if !exts.exists(file.toString.endsWith(_))) yield file

Which could be called like this:

val files = Array(new File("a.png"),new File("a.txt"),new File("a.jpg"))
val filtered = notEndsWith(files, "png", "jpg").toList

Upvotes: 1

Related Questions