I understand Ruby and Python\'s yield. What does Scala\'s yield do?
Yes, as Earwicker said, it's pretty much the equivalent to LINQ's select
and has very little to do with Ruby's and Python's yield
. Basically, where in C# you would write
from ... select ???
in Scala you have instead
for ... yield ???
It's also important to understand that for
-comprehensions don't just work with sequences, but with any type which defines certain methods, just like LINQ:
map
, it allows for
-expressions consisting of a
single generator.flatMap
as well as map
, it allows for
-expressions consisting
of several generators.foreach
, it allows for
-loops without yield (both with single and multiple generators).filter
, it allows for
-filter expressions starting with an if
in the for
expression.yield is more flexible than map(), see example below
val aList = List( 1,2,3,4,5 )
val res3 = for ( al <- aList if al > 3 ) yield al + 1
val res4 = aList.map( _+ 1 > 3 )
println( res3 )
println( res4 )
yield will print result like: List(5, 6), which is good
while map() will return result like: List(false, false, true, true, true), which probably is not what you intend.
val aList = List( 1,2,3,4,5 )
val res3 = for ( al <- aList if al > 3 ) yield al + 1
val res4 = aList.filter(_ > 3).map(_ + 1)
println( res3 )
println( res4 )
These two pieces of code are equivalent.
val res3 = for (al <- aList) yield al + 1 > 3
val res4 = aList.map( _+ 1 > 3 )
println( res3 )
println( res4 )
These two pieces of code are also equivalent.
Map is as flexible as yield and vice-versa.