7

I'm reading a book on scala programming (the Programming in Scala), and I've got a question about the yield syntax.

According to the book, the syntax for yield can be expressed like: for clauses yield body

but when I try to run the script below, the compiler complains about too many arguments for getName

def scalaFiles = 
  for (
    file <- filesHere
    if file.isFile
    if file.getName.endsWith(".scala")
  ) yield file.getName {
    // isn't this supposed to be the body part?
  }

so, my question is what is the "body" part of the yield syntax, how to use it?

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
Void Main
  • 2,241
  • 3
  • 27
  • 36

1 Answers1

17

Shortly, any expression (even that that return Unit), but you must enclose that expression into the brackets or just drop them down (works only with a single statement expressions):

def scalaFiles = 
  for (
    file <- filesHere
    if file.isFile
    if file.getName.endsWith(".scala")
  ) yield {
    // here is expression
  }

code above will work (but with no sense):

scalaFiles: Array[Unit]

Next option is:

for(...) yield file.getName

and as a tip, you can rewrite your for comprehension like that:

def scalaFiles = 
      for (
        file <- filesHere;
        if file.isFile;
        name = file.getName;
        if name.endsWith(".scala")
      ) yield {
        name
      }
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228