斯卡拉;如何迭代列表并在每次迭代中迭代另一个列表

时间:2016-06-28 09:13:40

标签: scala

我会尽力解释我的问题。

所以我在交货中有一个库存物品清单。我希望能够遍历此列表并通过遍历产品列表找到匹配的产品ID,直到库存项目列表和产品列表的产品ID匹配,然后增加产品数量。

所以StockItem类看起来像这样:

case class StockItem(val spiId : Int, val pId :Int, val sdId :Int, val quan : Int)

我的Product类看起来像这样:

case class Product(val prodId : Int, val name : String, val desc : String, val price : Double, var quantity : Int, val location : String)

我有一个方法来查找所有具有特定spId的StockItem,它返回一个StockItems列表:

def findAllItemsInSP(sdId: Int): List[StockPurchaseItem] = stockPurchaseItems2.filter(_.sdId == sdId)

我有另一种方法未完成迭代这个列表并增加每个产品的数量:

    def incrementStock(spID: Int){
      val items = StockPurchaseItem.findAllItemsInSP(spID)

    for (i <- items){
      if(i.pId == products.prodId)
    }
  }

产品是一组Product对象。很明显,products.prodId并不起作用,因为我需要引用产品Set的一个元素,而不是整个集合。我不知道如何在产品组中找到匹配的产品ID。给予任何帮助,我将非常感激。

注意:sdId和spId指的是同一个东西。

非常感谢 济

4 个答案:

答案 0 :(得分:2)

1st - case class的所有参数都是自动类值,因此您不需要这些val标签。

第二 - 您说“有一种方法可以找到具有特定spId的所有StockItem”,但代码正在过滤_.sdId == sdId。 SPID? SDID?有点混乱。

3rd - 你说“products是一组Project对象。”你的意思是Product个对象吗?我没有看到任何“项目”代码。

因此,您可以做的一件事是将items设为Map[Int,Int],将pId转换为数量,但默认值为零。

val items = StockPurchaseItem.findAllItemsInSP(spID).map(x => (x.spId, x.quantity)).toMap.withDefaultValue(0)

现在,您可以浏览products,将每个数量增加items(spId)

products.foreach(p => p.quantity += items(p.spId)) // or something like that

答案 1 :(得分:2)

您可以使用'for-comprehension'Docs以类似于下面的方法执行此操作。

val stockItems: List[StockItem] = ???
val products: List[Product] = ???
val result: List[Product] = for{
    item <- stockItems
    p <- products
    if p.prodId == item.pId
} yield { p.copy(quan = p.quan + 1) } //I expect you'd want different logic to this

答案 2 :(得分:0)

class MyClass<T>:T //here is the question is it possible dynamic inheritence
{

}

答案 3 :(得分:-1)

好的,我已经设法做了我想做的事情,创建了一个新产品,其中包含具有该产品ID的现有属性,然后添加到数量中。

def incrementStock(spID: Int){
      val items = StockPurchaseItem.findAllItemsInSP(spID)

    for (i <- items){
      var currentProd: Product = Product(Product.findProduct(i.pId).get.prodId, Product.findProduct(i.pId).get.name, Product.findProduct(i.pId).get.desc, Product.findProduct(i.pId).get.price, Product.findProduct(i.pId).get.quantity, Product.findProduct(i.pId).get.location)
      currentProd.quantity += i.quan

      products -= (findProduct(i.pId).get)
      products = products + currentProd
    }

    printProductInfo()
  }
相关问题