Loom
Loom

Reputation: 9986

Boolean operators in filter of list

I am trying to filter a list of files by two conditions. And the following code works

import java.io.File

val d = new File("/home/loom/shp")
val dirList = d.listFiles.filter(_.isDirectory).toList
dirList.map({
      _.listFiles.filter(f => f.isFile).filter(f => f.getName.endsWith("shp")).toList.map(println)

   // !! Inducde an error
   // _.listFiles.filter((f => f.isFile) && (f => f.getName.endsWith("shp"))).toList.map(println)
})

However, if I tried to combine both conditions in one filter condition (as it is shown in the commented line), I have received the following error message:

Error:(32, 27) missing parameter type _.listFiles.filter((f => f.isFile) && (f => f.getName.endsWith("shp"))).toList.map(println)

It claims that I missed the parameter type. What should I correct to make my code work?

Upvotes: 0

Views: 96

Answers (1)

Travis Brown
Travis Brown

Reputation: 139038

You're trying to use the boolean && operator on two functions, which simply won't work. What you want is a function from File to Boolean, which you can write like this:

_.listFiles.filter(f => f.isFile && f.getName.endsWith("shp")).toList.map(println)

f.isFile is a boolean and f.getName.endsWith(...) is a boolean, so && will do what you expect.

Upvotes: 3

Related Questions