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
)
什麼是建於法
高清的findAll = this.products.toList.sortBy(_。EAN) – swaheed 2014-10-20 15:42:04
爲什麼我們使用_.ean? – swaheed 2014-10-20 15:42:24
,因爲'sortBy'需要一個指定排序鍵的lambda。在這種情況下,你按'ean'排序 – 2014-10-20 15:48:11