2014-10-20 88 views
0

意味着我在Scala语言新,并从书中的教程以下斯卡拉这里打球是代码.map函数的用途是什么,以及那个_是什么。在斯卡拉

package models 
case class Product(ean: Long, name: String, description: String) 
object Product { 
var products = Set(
Product(5010255079763L, "Paperclips Large", 
"Large Plain Pack of 1000"), 
Product(5018206244666L, "Giant Paperclips", 
"Giant Plain 51mm 100 pack"), 
Product(5018306332812L, "Paperclip Giant Plain", 
"Giant Plain Pack of 10000"), 
Product(5018306312913L, "No Tear Paper Clip", 
"No Tear Extra Large Pack of 1000"), 
Product(5018206244611L, "Zebra Paperclips", 
"Zebra Length 28mm Assorted 150 Pack") 
) 
def findAll = this.products.toList.sortBy(_.ean) 
def findByEan(ean: Long) = this.products.find(_.ean == ean) 
def save(product: Product) = { 
findByEan(product.ean).map(oldProduct => 
this.products = this.products - oldProduct + product 
).getOrElse(
throw new IllegalArgumentException("Product not found") 
) 
} 
} 

上面的完整代码,我有一些问题了解一些代码行,请帮助我

def findByEan(ean: Long) = this.products.find(_.ean == ean) 

什么是_。为什么在这一行中使用_.ean

什么呢精细方法返回

findByEan(product.ean).map(oldProduct =>this.products = this.products - oldProduct + product 
) 

什么是建于法

回答

1

map使用.MAP是一种将转化的高阶函数通用容器的内容。

在这种情况下,容器是Option,由findbyEan返回。 Option可以是Some(x),在这种情况下它包含xNone,在这种情况下它不包含值。

map只适用于第一种情况下的转换,即如果它是None它将保持None


_是lambdas参数的简写。

find(_.ean == ean)直接转化为find(p => p.ean == ean)(当然,模变量名,我把它叫做p

+0

高清的findAll = this.products.toList.sortBy(_。EAN) – swaheed 2014-10-20 15:42:04

+0

为什么我们使用_.ean? – swaheed 2014-10-20 15:42:24

+0

,因为'sortBy'需要一个指定排序键的lambda。在这种情况下,你按'ean'排序 – 2014-10-20 15:48:11