scala> (1 to 10).iterator.map{_ * 2}.toList
res1: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
scala> (1 to 10).view.map{_ * 2}.force
res2: Seq[Int] =
view
produces a lazy collection/stream. It's main charm is that it won't try and build the whole collection. This could prevent a OutOfMemoryError or improve performance when you only need the first few items in the collection. iterator
makes no such guarantee.
One more thing. At least on Range
, view
returns a SeqView
, which is a sub-type of Seq
, so you can go back or start again from the beginning and do all that fun sequency stuff.
I guess the difference between an iterator and a view is a matter of in-front and behind. Iterators are expected to release what has been seen. Once next
has been called, the previous is, hopefully, let go. Views are the converse. They promise to not acquire what has not been requested. If you have a view of all prime numbers, an infinite set, it has only acquired those primes you've asked for. It you wanted the 100th, 101 shouldn't be taking up memory yet.