TakeWhile is used to take a set of elements until a predicate is satisfied. It can be defined formally as follows:
def takeWhile(p: (A) ⇒ Boolean): Traversable[A]
Let's see an example as follows:
// Given an infinite recursive method creating a stream of odd numbers.
def odd: Stream[Int] = {
def odd0(x: Int): Stream[Int] =
if (x%2 != 0) x #:: odd0(x+1)
else odd0(x+1)
odd0(1)
}
// Return a list of all the odd elements until an element isn't less then 9.
odd takeWhile (x => x < 9) toList
You will get the following output:
res11: List[Int] = List(1, 3, 5, 7)
In Scala, if you want to omit a set of elements till a predicate is satisfied, you should use dropWhile. We will see some examples of this in the next subsection.