Changing map value in Groovy

This is about a very simple program that I write in Groovy.

I defined a map inside the method:

  def addItem() 
  {
    print("Enter the item name: ")
    def itemName = reader.readLine()
    print("Enter price : ")
    def price = reader.readLine()
    print("Enter barcode : ")
    def barcode = reader.readLine()
    data[itemName] = ['price' : price, 'barcode' : barcode]
  }

The problem is that I do not know how to update one value inside another method. Here is what I tried:

  def updatePrice() 
  {
    print("Enter the item name: ")
    def itemName = reader.readLine()
    print("Enter new price : ")
    def price = reader.readLine()
    data[itemName] = ['price' : price]
  }

Such work. It changes the price value, but also changes the barcode value to "null", apparently because it is being rewritten ... nothing.

Basically, I need a code to change the price, but leave the barcode as is. Any ideas on how I can do this?

Sorry if this is a ridiculously elementary question, but I'm still very new to programming.

+3
source share
1 answer

, . . Java:

data[itemName].set('price', price)

, itemName, :

data[itemName].['price'] = price

, Map.keyname. , :

data.itemName.price = price

, :

println data.itemName.price // prints the price value for an item
+7

Source: https://habr.com/ru/post/1722832/


All Articles