Understanding foldLeft in Scala
Join the DZone community and get the full member experience.
Join For FreeAs 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 Jelle Victoor, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments