Scala collections let you "fold" the data in the collection into a single result. In the Scaladoc, it says that it "Folds the elements of this traversable or iterator using the specified associative binary operator." Let's play with this concept. Since fold() is the most flexible and powerful, let's warm up by looking at the simpler foldLeft and foldRight methods. These fold* operations will apply to a collection, so let's create a simple one: scala> val a = List(1,2,3) a: List[Int] = List(1, 2, 3) scala> a.foldLeft(7)(_+_) res1: Int = 13 What just happened? We created a List of integers, and called foldLeft on the List. We provided two parameters. The first is the start value, in this case 7. The second is a binary operation, in this case an addition. Since foldLeft applies the binary operation to the start value and each of the elements in the collection, going left to right, the steps to the result are: 7 + 1 = 8 8 + 2 = 10 10 + 3
Musings on Tests, Quality, Tools, Projects and more. By Steve Page