Functional Programming in Scala (2) — The Map function

Mallika Kulkarni

The scala map function converts one collection A to another B by applying a function to every element in A .

Simply put, you can call the map function on your collection, pass it a function, or an anonymous function, and transform each element of the collection.

For simple transformations, you can very well use an anonymous function.

val list = List(1,2,3)
val doubled = =>
elem * 2
println(doubled) // Output List(2, 4, 6)

This is a very basic example of what the map function does for you. In the above example, you call the map function on the original list list , apply an anonymous function to each element of the list. This operation returns another list with the doubled elements.

You can even convert a list of strings to a list of numbers

val list = List("one","two","three")
val lengths =
println(lengths) // Output List(3, 3, 5)

A cool thing is that you can also pattern match from inside of a map function — (A post on pattern matching in just a little time)

val list = List("one","two","three")
val patterns ={
case "one" => Some(1)
case "two" => Some(2)
case _ => None
println(patterns) // Output List(Some(1), Some(2), None)
println(patterns.flatten) // Output List(1, 2)

In the above example, we use pattern matching directly from inside a map function. We transform one to a Some(1), two to a Some(2) and any other string to an absent optional value None. To transform the List[Option[Int]] to a List[Int] and drop all absent options, just flatten the resulting list.

The function that is passed into the map method, can be as long, or as complicated as necessary. When the function becomes long, or complicated enough, you can define a function and pass it into the map.

def mapfn(a: Int) : Int = {
a * 2

def map4 = {
val list = List(1, 2, 3)
val doubles =
} // Output List(2, 4, 6)

If you want to transform only select values based on a condition that the values match, you can filter the values first, and then transform them.

def map5 = {
val list = List(1, 2, 3)
val doubles = list.filter(_ > 1).map(_*2)
} // Output List(4, 6)

The above example first filters the values of list for all values > 1 , and the doubles those selected values.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade