More Than Five
More Than Five

Reputation: 10419

Setting the property in a Map

I have a String variable c that I want to set in a map.

def c = "tony"
def methinks = [c:"bb"]

I want methinks[tony] = "bb"

but I get

methinks[c] = "bb"

Any tips

Upvotes: 1

Views: 69

Answers (2)

Paweł Piecyk
Paweł Piecyk

Reputation: 2789

You can access map values with dot notation or with []. It seems that you've mixed it up :) You can do it like below:

def methinks = [:]
c = "tony"
methinks."$c" = "bb"
assert methinks."$c" == "bb"

or:

def methinks = [:]
c = "tony"
methinks[c] = "bb"
assert methinks[c] == "bb"

As you can see the second version looks definitely better.

After question update: You're still mixing notations but @Opal provided exact solution to your problem.

Upvotes: 4

Opal
Opal

Reputation: 84756

It all works as expected:

def methinks = [:]
c = "tony"
methinks[c] = "bb"
assert methinks.tony == "bb"

After question update:

You need to escape c variable because it will be treated literally (as c sign) See:

def c = "tony"
def methinks = [(c):"bb"]
assert methinks.tony == 'bb'

Upvotes: 4

Related Questions