1

I have been navigating map structures fine for a long time now. Yet, for some reason, the root of this problem escapes me. I've tried bracket notation as well, no luck.

Why doesn't the final output (null) return "[serverinfo:[listenPort:19001]]"

If I replace the two instances of ' "$instanceName" ' with simply ' services ', it works.

String instanceName = "Services"
Map serverNode = [
    instances:[
        "$instanceName":[
            serverinfo:[
                listenPort:19001
            ]
        ]
    ]
]

println "$instanceName"
println serverNode.instances
println serverNode.instances."$instanceName"

//output 
Services
[Services:[serverinfo:[listenPort:19001]]]
null

1 Answer 1

3

The type of "$instanceName" is GStringImpl, not String. It's a common mistake (and hard to find!)

def serverNode = [
    instances:[
        ("$instanceName" as String):[
            serverinfo:[
                listenPort:19001
            ]
        ]
    ]
]

as stated by @tim_yates in comment, if your interpolated string is as simple as in this example (ie ,"${property}"), then you can use the (property) syntax : Groovy put the value of the property as a key, not the word "property"

Sign up to request clarification or add additional context in comments.

4 Comments

Or (instanceName):[
yes you're right, and it's much better than my answer :-) I was answering more strictly as this question about gstring in map (but the result is..ugly)
Completely agree, and they do mention interpolation, so I'm guessing their actual code is more complex ;-)
Thank you so much, this significantly improved my ability to work with maps, and answered a particularly frustrating little detail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.