As I’m working on some scala code the last few weeks, i have come across some functions in the scala api that I didn’t understand right away. One of those functions was foldLeft, FoldLeft is a relative easy method, but the scaladoc is not quite clear.
Applies a binary operator to a start value and all elements of this list, going left to right.
What the method actually does is apply a method on all the elements of a Sequence and accumulating it a variable. The initial value of that variable is give as first parameter, the second parameter is the function you apply.
In java it would like this
T accumulator = initialValue;
for(X listItem : list){
accumulator = method(accumulator, listItem);
}
return accumulator;
Take
val list = List(1,2,3) list.foldLeft(0)(_ + _)
The first parameter of the function given as argument is the accumulator, the second is the current value (or listItem in the java example). foldLeft results in 6.Tweet