Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala - yield syntax

Tags:

yield

scala

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?

like image 420
Void Main Avatar asked Mar 21 '12 00:03

Void Main


People also ask

How do you use yield in Scala?

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.

Why yield is used in Scala?

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.

What is yield in spark?

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.

DO FOR loops yield?

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.


1 Answers

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
      }
like image 58
om-nom-nom Avatar answered Nov 20 '22 01:11

om-nom-nom