Search code examples
scalaseqfoldleft

Deciding between use of foldleft() or Seq.newBuilder in Scala


I have some code where I need to add elements to a sequence while iterating over another one. Which way is the 'preferred' or rather the better way of doing that in scala and why?:

Way 1:

val builder = Seq.newBuilder[String]    
for(i <- iterator){
builder += i  //Everytime I want to add a new element    
}

Way 2:

val stringSeq = iterator.foldLeft(Seq[String]()){
case (acc, i) => i +: acc
}

Solution

  • I would say Way 2 is more idiomatic and feels more functional, as you do not create mutable state.

    The Way 1 seems to be a bit more imperative, as it resembles for as it is used in the object oriented programming.

    However Scala has both OOP elements and FP elements. I guess you should use a construct, which works better for you, due to for example performance reasons (however I don't think your example is the case, as appending to the head of Seq should be fast).

    PS. your generator should be <- not < and it is foldLeft (capital L)