为什么我不能在Scala中为此密钥更新此可变Map的值?

时间:2017-01-12 06:32:12

标签: scala

我有一个函数需要通过递减与传递给函数的键相关联的值来更新可变Map。它看起来像这样:

def selectProduct(product: String, insertedAmount: Float): (String,String) = {
    val price = products(product)
    val returnedProduct = if (insertedAmount >= price) product else ""
    if (returnedProduct != "") {
      inventory.update(product, inventory(product) - 1)
    }
    val message = display.displayMessage(product, returnedProduct)
    (returnedProduct, message)
}

库存定义如下:

def inventory = mutable.Map[String, Int](
  product1 -> 3,
  product2 -> 3,
  product3 -> 3
)

我设置了测试以检查在selectProduct中选择项目后,库存应该少一个该项目。此测试失败。我已验证该项目已正确选择。我尝试用def和val声明库存值。我试过在REPL中做这个,我想做的工作就好了。为什么这个值不会更新?

更新:测试代码

class VendingMachineSpec extends UnitSpec {

def vendingMachine = new VendingMachine()

it should "remove a purchased item from the inventory" in {
  val sixtyFiveCents = vendingMachine.coinOp.insertCoin(QUARTER, vendingMachine.coinOp.insertCoin(QUARTER, vendingMachine.coinOp.insertCoin(NICKEL, vendingMachine.coinOp.insertCoin(DIME, Coins.coins(PENNY)))))
  assert(sixtyFiveCents == SIXTY_FIVE_CENTS)

  val results = vendingMachine.selectProduct(product1, sixtyFiveCents)
  val product = results._1
  val message = results._2
  assert(product == product1)
  assert(message == "Thank you!")

  assert(vendingMachine.inventory(product1) == 2)
}
}

1 个答案:

答案 0 :(得分:3)

问题在于inventory的定义。您已将inventory定义为:

def inventory = mutable.Map[String, Int](???)

通过将其定义为def,您可以确保在使用库存时重新进行清点。所以假设你有:

val x = inventory
val y = inventory

xy都指向不同的对象。

要使您的代码正常工作,您必须用

替换库存的定义
val inventory = mutable.Map[String, Int](???)

lazy val inventory = mutable.Map[String, Int](???)
相关问题