Following Scala courses on Coursera, Martin Odersky showed an example code which is:
1 to 5 map ( i => i*i )
And he said the Range gets transformed to a Vector because they share the same interface (IndexedSeq) and the result could not be represented as a Range
(it was more clear in its example since he generated a pair which is not representable as a Range).
I’m not sure to understand because I think he said previously that in a for expression the 1st generator will determine the kind of element that will be yielded, and it seems not always true, at least for Range.
And I’m not sure to understand why the output is Vector, because Vector may not be the only other one implementation that can represent the result computed above.
Can someone help me understand this part please?
mapsecretly takes aCanBuildFromas an implicit argument. Its job is to produce a new collection given the one you’ve already got (and the type of the contents). SinceRangecan’t contain arbitrary stuff–not even arbitrary integers–there is noCanBuildFromthat produces aRange. The most specific supertype ofRangethat does have aCanBuildFromisIndexedSeq. The collection that is actually built by this is aVector.