【问题标题】:Why can't I update this mutable Map's value for this key in Scala?为什么我不能在 Scala 中为这个键更新这个可变映射的值?
【发布时间】:2017-01-12 20:14:37
【问题描述】:

我有一个函数,我需要通过递减与传递给函数的键关联的值来更新可变 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)
}
}

【问题讨论】:

  • 你能告诉我们你的测试代码吗?
  • 如果您在调整后打印调整后的条目,或者在调试器中运行它并检查值会发生什么?这将有助于找出问题所在。例如,如果您不小心将 product1 的价格设置为超过 65 美分怎么办?
  • @TheArchetypalPaul 打印出来的值显示与 product1 键关联的值始终为 2。我围绕此函数进行了多次测试,值始终为 2。
  • 我的意思是,当我在 selectProduct 函数的 if 语句中打印出来时,该值始终为 2
  • 如果函数内没问题,但外面不对,那么你看的不是同一个对象,

标签: scala


【解决方案1】:

问题在于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](???)

【讨论】:

  • 我已经尝试过使用 val 并且在测试中得到了相同的结果。
  • 问题出在我的测试中的 VendingMachine 定义。感谢您提出 def vs val
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 1970-01-01
  • 2015-02-03
相关资源
最近更新 更多