Consider this SO thread.
It is not easy to understand how things work (or why they do this way) in these two cases:
def compute(n: Int) = { println("Computing "+n); n * 2 }
// Example 0
val v0 = List.range(1, 4).view.flatMap(n => List(1,2).map(k => compute(n)))
v0(0) // Computing 1
// Computing 1
// Computing 2
// Computing 2
// Computing 3
// Computing 3
// Computing 1
// Computing 1
// Example 2
val v2 = List.range(1, 4).view.flatMap(n => List(1,2).view.map(k => compute(n)))
v2(0) // Computing 1
The result of example 0 is somewhat unexpected (as the SeqView nature is preserved on flatmap, even though the flatmap’s production is not a view). I also think that the scala-docs page on views should include some information about this (no info about SeqViewN
, the type of values resulting from flatmapping a view, seems to be available on the web).
Can somebody explain what is happening under-the-hood? It is not easy to trace the calls (and the intended semantics) along List
, SeqLike
, SeqViewLike
, TraversableViewLike
and the like.