Evan P
Evan P

Reputation: 1817

Yielding with For-loop and pass to match-case Expression

I was experimenting with the following code;

(for (f <- (new File(".")).listFiles() if !f.isDirectory) yield f) match {
  case x:File => println(x.getAbsoluteFile)
  case _ => println(_)
}

Obviously I am wrong somehow, as I am getting the following Error

scrutinee is incompatible with pattern type;
 found   : java.io.File
 required: Array[java.io.File]
    case x:File => println(x.getAbsoluteFile)
           ^

What I was trying to do is pretty obvious; I tried to get each yielded value from the for-loop and pass it to a match-case "filter". I am not interesting in writing a better File tree filter rather than knowing the reason of the Error that I am getting and if it is possible to fix it (or rewrite somehow else).

Cheers!

Upvotes: 0

Views: 92

Answers (1)

om-nom-nom
om-nom-nom

Reputation: 62835

Just a few symbols away:

for (f <- (new File(".")).listFiles() if !f.isDirectory) f match {
  case x:File => println(x.getAbsoluteFile)
  case _ => println(_)
}

The diff is

yield f)
{ f 

In your case you're first processing (listing|filtering|yielding one-by-one) whole collection and only then match whole result.

Upvotes: 2

Related Questions