map {}和map()之间有什么区别

时间:2016-08-18 05:40:39

标签: scala

从此链接显示一些Scala示例:
http://spark.apache.org/docs/latest/mllib-collaborative-filtering.html

map{}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)
}

2 个答案:

答案 0 :(得分:4)

map是一个接受函数作为参数的方法。因此习惯上调用map就像调用方法一样:map(aFunction)。但是,Scala在语法方面提供了很多灵活性/简洁性:

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 readable "infix notation" for single parameter methods 
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)

答案 1 :(得分:3)

val a = list.map(_.split(','))

// the above is a shorthand for
val a = list.map({ case i => i.split(',') })

// Now lets consider this
val a = list.map { case (a, b) => a + b }

// or this
val a = list map { case (a, b) => a + b }

// some people like the above ways of writing
// because they consider of less brackets as cleaner code.
// but the above two are another way to write
val a = list.map({ case (a, b) => a + b })

这里要理解的是,在Scala中,您可以使用空格而不是.来访问实例方法。

基本上,

// lets say you have a class A
case class A(i: Int) {

  def merged[B](b: B): String = i.toString + " :: " + b.toString

}

//Now, lets say you have an instance of A
val a = A(5)
// and an instance of String
val s: String = "abcd"

// Now, if you write
val merged = a merged s
// it is syntactic sugar for
val merged = a.merged(s)

同样,List[A]有一个方法map[B](f: A => B): List[B]

val list = List[Int](1, 2, 3)

// so when you write
val list2 = list map { case i => i + 1}

// its syntactic sugar for,
val list2 = list.map({ case i => i + 1 })

// There is a lot going on here
// if we were to do everything step by step

// first you are creating a partial function
val pf: PartialFunction[Int, Int] = { case i => i + 1 }

// Now, PartialFunction[Int, Int] is a subtype of Int => Int
// so we can refer to it as a Int => Int
val f: Int => Int = pf

// Now we pass it as an argument to map
val list2 = list.map(f)