Platinum Partner
java,scala,languages,tips and tricks

Understanding foldLeft in Scala

 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 is an integer and method does “accumulator + listItem”, we get a method that adds all integers with eachother starting from the initial value.

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.




Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}