scalalazy-evaluationscala-collections

What is the difference between List.view and LazyList?


I am new to Scala and I just learned that LazyList was created to replace Stream, and at the same time they added the .view methods to all collections.

So, I am wondering why was LazyList added to Scala collections library, when we can do List.view?

I just looked at the Scaladoc, and it seems that the only difference is that LazyList has memoization, while View does not. Am I right or wrong?


Solution

  • Stream elements are realized lazily except for the 1st (head) element. That was seen as a deficiency.

    A List view is re-evaluated lazily but, as far as I know, has to be completely realized first.

    def bang :Int = {print("BANG! ");1}
    
    LazyList.fill(4)(bang)  //res0: LazyList[Int] = LazyList(<not computed>)
    Stream.fill(3)(bang)    //BANG! res1: Stream[Int] = Stream(1, <not computed>)
    List.fill(2)(bang).view //BANG! BANG! res2: SeqView[Int] = SeqView(<not computed>)