zam zam - 1 month ago 8
Scala Question

Swapping semi colon for curly braces

In the book, Programming In Scala, it says:

"you can use curly braces instead of parentheses to surround the generators and filters. One advantage to using curly braces is that you can leave off some of the semi colons that are needed when you use parentheses".

I'm trying to do this with this bit of code but can't seem to manage it. Can you guys fill them in for me so I can see how this is done.

Thanks

def fileLines(file:java.io.File) =
scala.io.Source.fromFile(file).getLines.toList

def grep(pattern:String) =
for(
file<-filesHere
if(file.getName.endsWith(".scala")); //I dont want to use this semi-colon
line<-fileLines(file)
if(line.trim.matches(pattern))
)
println(file +":" + line.trim)

val filesHere = new java.io.File(".").listFiles;
grep(".*gcd.*")

Answer

You can just change parenthesis in for-comprehesion to curly braces (exactly as the book tells you):

def grep(pattern:String) = {
  for {
    file <- filesHere
      if(file.getName.endsWith(".scala"))
    line <- fileLines(file)
      if(line.trim.matches(pattern))
  } println(file +":" + line.trim)
}