Christian Yonathan S. Christian Yonathan S. - 3 months ago 10
Scala Question

What is the difference between map{} and map()

From this link showing some Scala examples:
http://spark.apache.org/docs/latest/mllib-collaborative-filtering.html



what is the difference between

map{}
and
map()
?


val ratings = data.map(_.split(',') match { case Array(user, item, rate) =>
Rating(user.toInt, item.toInt, rate.toDouble)
})

val usersProducts = ratings.map { case Rating(user, product, rate) =>
(user, product)
}

Answer

map is a method which accepts a function as an argument. So map customarily is called just like methods get called: map(aFunction). However, Scala provides a lot of flexibility / shorthands in its syntax:

val list = List((1,2),(3,4))

//An ordinary method call. The braces just evaluate to an anonymous function
val a = list.map({ case (a, b) => a + b }) // List(3,7)  


// Now lets define a non anonymous function of the same type as above:
def  func(x: (Int,Int)) = x match {case (a,b) => a + b}

// Scala allows this kind of syntax which reads like normal english :) 
val a = list map func // List(3,7)

//Now to the main point you asked, this syntax uses the same readable form as above 
//but uses an anonymous function.  
val a = list map {case (a,b) => a + b} // List(3,7)
Comments