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?
yield keyword will returns a result after completing of loop iterations. The for loop used buffer internally to store iterated result and when finishing all iterations it yields the ultimate result from that buffer. It doesn't work like imperative loop.
The yield keyword is used because the result of each for loop iteration is stored in a list (vector) or it collects the list of output and saves it in the vector.
Yield is a keyword in scala that is used at the end of the loop. We can perform any operation on the collection elements by using this for instance if we want to increment the value of collection by one. This will return us to the new collection.
For each iteration of your for loop, yield generates a value which is remembered by the for loop (behind the scenes, like a buffer). When your for loop finishes running, it returns a collection of all these yielded values. The type of the collection that is returned is the same type that you were iterating over.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With