I am completely new to Scala. I've been playing around with LazyLists. Consider the following:
val fun: Int => Int = (x: Int) => {
println("PROCESSING...")
x + 1
}
val lazyList = LazyList(fun(1), fun(2), fun(3))
The snippet above prints "PROCESSING..." thrice, which indicates that all three elements of LazyList were computed. I found such behaviour to be rather unexpected for a lazy collection. So, I decided to print it:
println(lazyList) // which prints "LazyList(<not computed>)".
I thought it would print out LazytList(2, 3, 4). (I'm not completely sure, but it seems to me that Scala's println works for lazy collections sort of like the :sprint command in GHCi, dividing the collection in two parts: the evaluated and the unevaluated one.)
So, here are my questions, concerning this code:
- Why are no elements displayed as evaluated? If they are indeed unevaluated, what was this triple
"PROCESSING..."thing about? If not, why doesprintlnclaim so? - Why do we want
LazyList's arguments likefun(1)to be computed right away? Why do we cast away thecall-by-needstrategy when initializing? Are there any other cases where such a thing happens? Note that no output is produced when we usemapinstead of writing this down manually, as expected.