0

I wanted to know when both of them are doing the same thing, what can be possible use cases to use the first one over the second statement.

    val xs = List[Int](1,2,3,4,5,6)

for a list of numbers :

    for (x <- xs if x%2 == 0) 
           yield x*10 

same as :

    xs.filter(_%2 == 0).map(_*10)
Hammad Haleem
  • 1,374
  • 1
  • 16
  • 26

1 Answers1

4

I think that there is no performance difference. The code using the for loop under the hood will be translated into the code with filter and map (the details can varied depending on Scala version). It is matter of your preferences which version you want to use. See this answer for more details.

Community
  • 1
  • 1
Michał Komorowski
  • 6,198
  • 1
  • 20
  • 24
  • Thanks :) What you think would happen if the operation is being performed on a spark RDD ? ( I mean , if xs is a RDD ? ) – Hammad Haleem Feb 02 '16 at 07:32
  • Translation of for loop into the code with map/for is performed by a compiler. It means that it should work in the same way regardless of what kind of collection is used. – Michał Komorowski Feb 02 '16 at 07:36
  • makes sense :) Thanks. – Hammad Haleem Feb 02 '16 at 07:39
  • AFAIK for comprehension would use `withFilter` instead of `filter` when desugared which avoids intermediate collection. See http://stackoverflow.com/questions/19617378/withfilter-instead-of-filter – Łukasz Feb 02 '16 at 10:34