What is the difference between the methods iterator and view?

前端 未结 3 767
[愿得一人]
[愿得一人] 2020-12-05 02:58
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] =         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 03:20

    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.

提交回复
热议问题