fold

definition

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

demo

val prices: Seq[Double] = Seq(1.5, 2.0, 2.5)

// sum all the donut prices using fold function
val sum = prices.fold(0.0)(_ + _)

demo2

val donuts: Seq[String] = Seq("Plain", "Strawberry", "Glazed")

// create a String of all donuts using fold function
val singleString = donuts.fold("")((acc,s) => acc + s + " Donut ")

输出的内容是

scala> val singleString = donuts.fold("")((acc,s) => acc + s + " Donut ")
singleString: String = "Plain Donut Strawberry Donut Glazed Donut "

demo3

输出的结果与 demo2 等价,只不过将函数显式地定义在外面,比较好理解。

Last updated

Was this helpful?