prayagupadhyay
prayagupadhyay

Reputation: 31232

access groovy map by dynamic key

I want a construct a groovy map with dynamic key as below, and want to get the value by dynamic key. But I am not able to access it, it returns null for the same key.

class AmazonPackage {
    public static String WEIGHT = "WEIGHT"
}

class PackageTests {

   @Test
   void "map should return value by dynamic key" () {
       def map = [ ("${AmazonPackage.WEIGHT}") : 100, "id": "package001"]

       assert map['id'] == "package001"

       //assert map[("${AmazonPackage.WEIGHT}")] == 100
       //assert map."${AmazonPackage.WEIGHT}" == 100

       assert 2 == map.keySet().size()
       assert map."WEIGHT" == 100 //fails
    }

    @Test
    void "map should return value by simple key" () {
        def map = ["w" : 100]
        assert map."w" == 100
    }

}

Failure I get is,

Assertion failed: 

assert map."WEIGHT" == 100
       |   |        |
       |   null     false
       [WEIGHT:100, id:package001]

Upvotes: 2

Views: 7617

Answers (3)

rockympls
rockympls

Reputation: 321

I would recommend setting the map like so:

def map = [ (AmazonPackage.WEIGHT) : 100, "id": "package001"]

And doing your assertion like so:

assert map[AmazonPackage.WEIGHT] == 100

Upvotes: 1

doelleri
doelleri

Reputation: 19682

Unfortunately, the map key you are storing is a GString, not a String. This means the map is not considering those keys equal.

If you want to access your map with String values, you should store the key as a string:

def map = [ ("${AmazonPackage.WEIGHT}".toString()) : 100, "id": "package001"]
assert map."WEIGHT" == 100

Upvotes: 10

Sandeep Poonia
Sandeep Poonia

Reputation: 2188

First of all if you want to fetch value from a map using "." operator then you directly provide the key like map.key to fetch value for key 'key' from map.

Secondly, as the class for "${AmazonPackage.WEIGHT}" is GStringImpl and not a plain String object, you cann't fetch its value using simple "." operator, instead you should use get(). Also this get will return result only if you provide the key as a GStringImpl and not plain String object: map.get("${AmazonPackage.WEIGHT}")

Upvotes: 1

Related Questions