[Solved] Understanding map in Scala [closed]


1. .map in functional programming applies the function you want to each element of your collection.

Say, you want to add some data to each element in an array you have, which can be done as below,

scala> val data = Array("a", "b", "c")
data: Array[String] = Array(a, b, c)

scala> data.map(element => element+"-add something")
res10: Array[String] = Array(a-add something, b-add something, c-add something)

Here, I’m saying, on each element add something, but element is unnecessary because you are adding on every element anyway. So, _ is what represents any element here.

So, same map can be done in following way.

scala> data.map(_+"-add something")
res9: Array[String] = Array(a-add something, b-add something, c-add something)

Also, note that _ is used when you have one line mapping function.

2. collection(index) is the way to access nth element in a collection.

eg.

scala> val collection = Array(Vector(1039), Vector(1010), Vector(1002), Vector(926))
collection: Array[scala.collection.immutable.Vector[Int]] = Array(Vector(1039), Vector(1010), Vector(1002), Vector(926))

scala> collection(0)
res13: scala.collection.immutable.Vector[Int] = Vector(1039)

So, combining #1 and #2, in your case you are mapping the original collection and getting the first element.

scala> collection.map(_.head)
res17: Array[Int] = Array(1039, 1010, 1002, 926)

Refs

https://twitter.github.io/scala_school/collections.html#map

Map, Map and flatMap in Scala

solved Understanding map in Scala [closed]