consume items from a scala Iterator

The iterator in question is defined in IndexedSeqLike#Elements (source). A ticket was recently filed about the the inconsistent behaviour of take across different iterator implementations.

To really consume N items, call Iterator#next N times.

You might want to consider using Stream, which is a lazy (like Iterator), but is also immutable (unlike Iterator).

scala> val s = Stream(1, 2, 3)
s: scala.collection.immutable.Stream[Int] = Stream(1, ?)

scala> s.take(2).toList
res43: List[Int] = List(1, 2)

scala> s.take(2).toList
res44: List[Int] = List(1, 2)

scala> s.drop(2).toList
res45: List[Int] = List(3)

scala> {val (s1, s2) = s.splitAt(2); (s1.toList, s2.toList)}
res46: (List[Int], List[Int]) = (List(1, 2),List(3))

You want to consume the items, drop them. Note that most methods called on an Iterator will make that Iterator useless for further use -- useless in the sense that behavior is undefined and subject to change.


Thanks guys.

This is my solution to consume bunches of items from an Iterator:

  implicit def consumable(i: Iterator[_]) = new {
    def next(n: Int) = {
      (for (_ <- 1 to n) yield i.next()).iterator
    }
    def skip(n: Int) {
      (1 to n).foreach(_ => i.next())
    }
  }

any comments will be welcome.