Scala Collections: Part 3 - Exploring more operations

In the final post of this series, we're going to continue to look at the variety of operations in the Scala Collection API.

Let’s start with a few operations that builds on ideas we've already looked at.

TakeWhile

def takeWhile(p: (A) ⇒ Boolean): Traversable[A]

Takes the longest prefix of elements that satisfy a predicate.

This operation takes the ideas from the take operation and gives it more flexibility. Instead of having a static number of elements to return, we can now give a predicate to determine when to stop fetching elements.

Fold, FoldLeft, FoldRight

These three operations are pretty similar. They all take a start value and a function. The function takes two arguments. The first one is the accumulated value and the second is the value of the current element. Starting with the start value, they iterate the elements of the collection using the function given as an argument to fold the collection.