Over a million developers have joined DZone.

Understanding foldLeft in Scala

DZone's Guide to

Understanding foldLeft in Scala

· Java Zone ·
Free Resource

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

 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.

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}