什么是.map函数的用途,以及_的作用。斯卡拉意味着什么

时间:2014-10-20 15:27:00

标签: scala

我是scala语言的新手,并且遵循scala的书籍教程,这里是代码

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
)

在方法

中构建的.map有什么用?

1 个答案:

答案 0 :(得分:1)

map是一个高阶函数,它将转换应用于通用容器的内容。

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

map仅在第一种情况下应用转换,即如果它是None,它将保持None


_是lambdas参数的简写。

find(_.ean == ean)直接转换为find(p => p.ean == ean)(嗯,模拟变量名称,我称之为p