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("<default value>")(
     (prior, dataTuple) => {
       val (headerName, cell) = dataTuple
       if (headerName.equals(searchColumn)) cell else prior
     }
   )

Interested in Scala? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *