MiddaPhofidda MiddaPhofidda - 1 month ago 20
Scala Question

Merge collection operations

Look at the code below:

val a = List(1,2,3,4,5)
a.filter(_ >= 3).map(_ * 9).drop(1).take(2)


My understanding is that it this iterates through the list once for each operation, generating code similar to this:

for(i <- a) {
// filter
}
for (i <- afiltered) {
// map
}
for (i <- afilteredandmapped) {
// drop
}
..etc


Is there anyway to combine these operations, having chaining operations that only iterates once through the list? Generating such as below:

for (i <- a) {
// filter
// map
// drop
// take
}

Answer

Scala 2.8 collections introduced the notion of a Views, which are a lazy counterpart to the strict collections. It allows you to avoid the intermediate allocation of collections when applying multiple transformations on them.

You use them via calling .view on the collection, and when you want to materialize them you can do it via .force or toList/.toSeq:

val result = a
              .view
              .filter(_ >= 3)
              .map(_ * 9)
              .drop(1)
              .take(2)
              .force