Scala – Fold Right

  • date 30th May, 2021 |
  • by Prwatech |
  • 0 Comments

The foldRight work is relevant to both Scala's Mutable and Immutable assortment information structures.

The foldRight technique takes an affiliated parallel administrator work as boundary and will utilize it to implode components from the assortment. The request for navigating the components in the assortment is from option to left and thus the name foldRight. The foldRight technique permits you to likewise determine an underlying worth.

use case 1:

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

scala> val prices: Seq[Double] = Seq(1.5, 2.0, 2.5)
scala> val sum = prices.foldRight(0.0)(_ + _)

use case 2:

Create a String of all  using foldRight function
scala> val eduprwa: Seq[String] = Seq("Data", "Science", "Prwatech")
scala> println(s"All eduprwa = ${eduprwa.foldRight("")((a, b) => a + " eduprwa " + b)}")

use case 3:

scala> val prices: Seq[Int] = Seq(1, 2, 2)
scala> val sum = prices.foldRight(0.0)(_ - _)

Quick Support

image image