map, flatMap, filter and for comprehension in Scala

When map is applied on some collection of type A, it returns a new collection of the same type with elements of type B.

    val list = List(1,2,3) // this is calling apply method on companion object
    // map
    println( + 1)) // returns List (same type) of type Int
    println( + " is a number")) // returns List (same type) of type String

Takes a lambda that takes one param and returns boolean. Values are filtered when boolean is true.

  println(list.filter(_ % 2 == 0)) // prints 2

flatten (reduces) the hierarchy by one level each time it is applied

    val toPair = (x: Int) => List(x, x+1)

Example with both map and flatMap

val numbers = List(1, 2, 3, 4)
    val chars = List('a', 'b', 'c', 'd')
    val colors = List("White", "Black")
    val combinations = numbers.flatMap(n => chars.flatMap(c => => c + "" + n + " " + co)))

for comprehensions
since the above maps and flatMaps are difficult to read, we use for comprehensions and the compiler will transform the for-comprehension to maps and flatMaps for us

    val forCombinations = for {
        n <- numbers
        c <- chars
        co <- colors
    } yield "" + c + "" + n + " " + co

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


Mostly technology with occasional sprinkling of other random thoughts


Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates


A topnotch site


Just another site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: