Tuesday, July 8, 2014

How Does Scala List.map Function Work

When I was learning Scala I came across the List,map method.  It is defined as follows in the documentation ...

final def
map[B](f: (A) ⇒ B): List[B]

[use case] Builds a new collection by applying a function to all elements of this list.

How what does this mean and how can we use it?

Although from the definition it may look cryptic it becomes easier to understand once we have an example.   Let us see how to use List.map in Scala using a simple example -

Let us say you have defined a list of fruits as follows -

var fruits = List("Apple","Orange","Banana");

Now you want to convert each of the fruits into lower case and return another List.  This can be achieved very easily with List.map function.

var lowerCaseFruits = fruits.map(fruit => fruit.toLowerCase)

The map function is applied on the fruits list and each element is stored in the fruit element one by one. Then the element is converted to lower case using the String lower case function and then stored in another list which is eventually returned back.  In this case the output List is stored in the variable lowerCaseFruits.

There is more fun to List. The output of List.map can be again chained to another List.map.  Here is an example -

var listOfNumber = List(1,2,3)
var nums = listOfNumber.map(number => number * 2).map(number => number * number)

Can you guess what will be the output and why?

No comments:

Post a Comment