map, flatMap, filter and for comprehension in Scala
November 26, 2019 Leave a comment
.map
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
println(list)
// map
println(list.map(_ + 1)) // returns List (same type) of type Int
println(list.map(_ + " is a number")) // returns List (same type) of type String
.filter
Takes a lambda that takes one param and returns boolean. Values are filtered when boolean is true.
println(list.filter(_ % 2 == 0)) // prints 2
.flatMap
flatten (reduces) the hierarchy by one level each time it is applied
val toPair = (x: Int) => List(x, x+1)
println(list.flatMap(toPair))
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 => colors.map(co => c + "" + n + " " + co)))
println(combinations)
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
println(forCombinations)
Recent Comments