score:6

Accepted answer

note that the documentation on takewhile states:

reuse: after calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

so you shouldn't use i, after calling takewhile on it.


but to achieve what you want you can use the span method:

scala> val i = (1 to 8).iterator
i: iterator[int] = non-empty iterator

scala> val (onetothree, rest) = i.span(_ <= 3)
onetothree: iterator[int] = non-empty iterator
rest: iterator[int] = unknown-if-empty iterator

scala> onetothree.tolist
res1: list[int] = list(1, 2, 3)

scala> val fourtosix = rest.takewhile(_ <= 6)
fourtosix: iterator[int] = non-empty iterator

scala> fourtosix.tolist
res2: list[int] = list(4, 5, 6)

Related Query

More Query from same tag