Keys in the map are string by default. Let me confirm
this with below example.
HelloWorld.groovy
def countryCapitals = [India : "new Delhi", Australia : "Canberra"] indiaCapital = countryCapitals.get('India') australiaCapital = countryCapitals['Australia'] println "indiaCapital : $indiaCapital" println "australiaCapital : $australiaCapital"
Output
indiaCapital : new Delhi
australiaCapital : Canberra
How can you make the
value of particular variable 'x' as the key to the map?
You can do this by escaping the key adding parenthesis.
HelloWorld.groovy
def x = "India" def y = "Australia" def countryCapitals = [(x) : "new Delhi", (y) : "Canberra"] indiaCapital = countryCapitals.get('India') australiaCapital = countryCapitals['Australia'] println "indiaCapital : $indiaCapital" println "australiaCapital : $australiaCapital"
Output
indiaCapital : new Delhi
australiaCapital : Canberra
australiaCapital : Canberra
No comments:
Post a Comment