Gary Sieling

Scala fold example (fold over tuples)

The variations on “fold” let you condense a Scala collection into a single value.

This example shows how you might find a named column in a CSV file, by calling “zip” on the list of headers and cells, then doing a lookup with foldLeft:

val searchColumn = "Name"
val headers = "Name,Quantity,Amount"
val row = "Gary,10,100"

headers.split(",")
   .zip(
     row.split(",")
   ).foldLeft("")(
     (prior, dataTuple) => {
       val (headerName, cell) = dataTuple
       if (headerName.equals(searchColumn)) cell else prior
     }
   )
Exit mobile version