简体   繁体   中英

Scala Yield results of calculation using foreach/for

I wrote the following

val suspects  =   
tenCalls.foreach{f=>IllegalOddsCalcs.getOddsForMsisdnScala(f._2.toList)}

or it can be this

  val suspects = for (f <- tenCalls) 
  (IllegalOddsCalcs.getOddsForMsisdnScala(f._2.toList))  

When I run the above, the suspect list is always empty, as I have not used the yield. How can I use the yield with the above to populate the suspects, or should I be using something else?

foreach is stateful and returns Unit . You need to use map instead. Or you can add a yield after your for

val suspects = tenCalls.map(f=>...)

OR

val suspects = for(f <- tenCalls) yield {...}

I guess @Justin is right. The "foreach" paradigm is defined in:

scala.collection.generic.FilterMonadic

And its return type is "Unit" (or say, "void"). And in your case, you should use map:

abstract def map[B, That](f: (A) ⇒ B)(implicit bf: CanBuildFrom[Repr, B, That]): That

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM