Andrew Tobilko Andrew Tobilko - 3 months ago 8
Groovy Question

Key declaration with the value from the existing key which is defined before in the same map initialization

I've got a global map in

build.gradle
(the config is written on Groovy).

I want to know whether it's possible to ask for already existing keys (probably, they doesn't exist yet, I understand) during the map declaration by the map literal way after those places where these keys have been declared.

ext.app = [
versions: [k1:'v1', k2: 'v2'],
dependencies: [d1:'dep1:$versions.k1', d2:'dep2:$versions.k2']
^^^^^^^^^^^ ^^^^^^^^^^^
]


Just to say "I define a new key with the value of the key which possibly may be in my map".

newKey: map(existingKey)
|
V
newKey: existingValue


Tried to clarify it simply. Any assistance would be appreciated.

Answer

Groovy can't autoreference its maps. with will work fine, though:

app = [:].with {
    versions = [
        k1: 'v1', 
        k2: 'v2'
    ]
    dependencies = [
        d1:"dep1:$versions.k1",
        d2:"dep2:$versions.k2"
    ]
    it
}

assert app.dependencies.d1 == "dep1:v1"
assert app.dependencies.d2 == "dep2:v2"

In a with block, all method calls are delegated to the calling object, thus, a $versions.k1 will be rerouted to the map being created.

Note the it at the end of the with block, otherwise the app variable won't contain the map, but instead will contain whatever that closure return.

Comments