So I’m learning Scala and came across some examples like this:
val doubleEven = for (i <- 1 to 10; if i % 2 == 0)
yield i * 2
Now, what’s the added benefit to having this special syntax built into the for loop as opposed to the time-honored
val doubleEven = for(i <- 1 to 10){
if(i % 2 == 0)
yield i*2
}
style if?
EDIT: Of course, the latter example won’t actually work. But I was curious why the Scala folks decided to go with a separate syntax.
Contents of file
A.scala:Output of
scalac -Xprint:jvm A.scala:As you can see the compiler creates a
Rangefrom 1 to 10. Then it calls thewithFilteron thatRangeto filter all even numbers. And the last step is the call of themap-method with the multiplication with 2.Would your second example work the semantic would be a little bit different. Because it would execute the body of the loop in every iteration without filtering.
It is a matter of taste but I would prefer this: