How to use a variable for the key part of a map

前端 未结 2 1398
小鲜肉
小鲜肉 2021-01-30 10:03

Let\'s say I have

def A = \"abc\"
def X = \"xyz\"

how do I create a Map where, instead of

def map = [A:1, X:2]
         


        
2条回答
  •  借酒劲吻你
    2021-01-30 10:40

    Further to Joachim's answer, if you want to add entries to an existing map and the keys are variables, use:

    def map = [:]
    def A = 'abc'
    map[A] = 2
    

    If you use:

    map.A = 2
    

    It is assumed that you want to use the literal string 'A' as the key (even though there is a variable named A in scope.

    Update

    As @tim_yates pointed out in a comment, a key variable will also be resolved if you use:

    map."$A" = 2
    

    though personally I prefer to use the [A] syntax because refactoring tools might miss the "$A" reference if the variable is renamed

提交回复
热议问题