This is a question about the Scala compiler.
Let's say I have a List, and that I transform that list through several maps and flatMaps.
val myList = List(1,2,3,4,5)
val transformed = myList.map(_+1).map(_*2).flatmap(x=>List(x-1,x,x+1))
Let's say I transform it some more.
val moreTransformed = transformed.map(_-2).map(_/5).flatMap(x=>List(x/2,x*2))
My question can be divided into two parts
When generating the val for
transformed
, does the underlying Java bytecode create the intermediate lists? I am referring to the successive calls to map and flatMap in the computation oftransformed
. Can the Scala compiler compose these calls into a single flatMap? If I was operating on a list of objects, this would entail creation of fewer intermediate objects. If the compiler is naive and simply creates the intermediate objects, that could potentially result in considerable overhead for computations that involve long chains of map and flatMap.Let us say that of the two vals created above, I only use
moreTransformed
(the second val) in further computation. That is, I only usetransformed
(the first val) in the calculation ofmoreTransformed
and nowhere else. Is the Scala compiler smart enough not to create the List fortransformed
and to compute onlymoreTransformed
? Is it smart enough to compose all the functions intransformed
andmoreTransformed
so that only a single List, the value ofmoreTransformed
, is produced?