Scala Collections - Fold Method



fold() method is a member of TraversableOnce trait, it is used to collapse elements of collections.

Syntax

The following is the syntax of fold method.

def fold[A1 >: A](z: A1)(op: (A1, A1) ? A1): A1

Here, fold method takes associative binary operator function as a parameter. This method returns the result as value. It considers first input as initial value and second input as a function (which takes accumulated value and current item as input).

Usage

Below is an example program of showing how to use fold method −

Example

object Demo {
   def main(args: Array[String]) = {
      val list = List(1, 2, 3 ,4)
      //apply operation to get sum of all elements of the list
      val result = list.fold(0)(_ + _)
      //print result
      println(result)      
   }
}

Here we've passed 0 as initial value to fold function and then all values are added. Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

10
Advertisements