Scala Tutorial - Learn How To Use Fold Function With Examples

By Nadim Bahadoor | Last updated: March 16, 2018 at 14:29 pm

Overview

In this tutorial, we will learn how to use the fold function with examples on collection data structures in Scala. The fold function is applicable to both Scala's Mutable and Immutable collection data structures.

 

The fold method takes an associative binary operator function as parameter and will use it to collapse elements from the collection. The fold method allows you to also specify an initial value.

 

As per the Scala documentation, the definition of the fold method is as follows:


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

 

The fold method is a member of the TraversableOnce trait.

Steps

1. How to initialize a sequence of donut prices

The code below shows how to initialize a sequence of donut prices where each element in the sequence is of type Double.


println("Step 1: How to initialize a sequence of donut prices")
val prices: Seq[Double] = Seq(1.5, 2.0, 2.5)
println(s"Donut prices = $prices")

 

You should see the following output when you run your Scala application in IntelliJ:


Step 1: How to initialize a sequence of donut prices
Donut prices = List(1.5, 2.0, 2.5)

 

2. How to sum all the donut prices using fold function

The code below shows how to sum all the donut prices from the sequence by using the fold method.


println("\nStep 2: How to sum all the donut prices using fold function")
val sum = prices.fold(0.0)(_ + _)
println(s"Sum = $sum")

You should see the following output when you run your Scala application in IntelliJ:


Step 2: How to sum all the donut prices using fold function
Sum = 6.0

NOTE:

  • Note that we passed in a default or initial value of 0.0 to the fold method because the sequence of Donuts was of type Double.

3. How to initialize a Sequence of donuts

The code below shows how to initialize a Sequence of donuts where each element is of type String.


println("\nStep 3: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain", "Strawberry", "Glazed")
println(s"Elements of donuts1 = $donuts")

You should see the following output when you run your Scala application in IntelliJ:

Step 3: How to initialize a Sequence of donuts
Elements of donuts1 = List(Plain, Strawberry, Glazed)

 

4. How to create a String of all donuts using fold function

The code below shows how to create a String representation for all the donut elements in the Sequence and also append the word Donut to each element using the fold method.



println("\nStep 4: How to create a String of all donuts using fold function")
println(s"All donuts = ${donuts.fold("")((acc, s) => acc + s + " Donut ")}")

You should see the following output when you run your Scala application in IntelliJ:


Step 4: How to create a String of all donuts using fold function
All donuts = Plain Donut Strawberry Donut Glazed Donut 

 

5. How to declare a value function to create the donut string

The code below shows how to declare a Value Function to encapsulate the behaviour for creating a String representation for all donut elements.


println("\nStep 5: How to declare a value function to create the donut string")
val concatDonuts: (String, String) => String = (s1, s2) => s1 + s2 + " Donut "
println(s"Value function concatDonuts = $concatDonuts")

You should see the following output when you run your Scala application in IntelliJ:


Step 5: How to declare a value function to create the donut string
Value function concatDonuts = <function2>

 

6. How to create a String of all donuts using value function from Step 5 and fold function

The code below shows how to create a String representation for the donut elements by passing through the Value Function from Step 5 to the fold method.


println("\nStep 6: How to create a String of all donuts using value function from Step 5 and fold function")
println(s"All donuts = ${donuts.fold("")(concatDonuts)}")

You should see the following output when you run your Scala application in IntelliJ:


Step 6: How to create a String of all donuts using value function from Step 5 and fold function
All donuts = Plain Donut Strawberry Donut Glazed Donut 

This concludes our tutorial on Learn How To Use Fold Function With Examples and I hope you've found it useful!

 

Stay in touch via Facebook and Twitter for upcoming tutorials!

 

Don't forget to like and share this page :)

Summary

In this tutorial, we went over the following:

  • How to initialize a sequence of donut prices
  • How to sum all the donut prices using fold function
  • How to initialize a Sequence of donuts
  • How to create a String of all donuts using fold function
  • How to declare a value function to create the donut string
  • How to create a String of all donuts using value function from Step 5 and fold function

Tip

  • Review the tutorials on Mutable and Immutable collection data structures in Scala.

Source Code

The source code is available on the allaboutscala GitHub repository.

 

What's Next

In the next tutorial, I will show you how to use foldLeft function.

Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Technology and Finance Consultant with over 14 years of hands-on experience building large scale systems in the Financial (Electronic Trading Platforms), Risk, Insurance and Life Science sectors. I am self-driven and passionate about Finance, Distributed Systems, Functional Programming, Big Data, Semantic Data (Graph) and Machine Learning.
Other allaboutscala.com tutorials you may like: