Odd behaviour with Map in Groovy

前端 未结 2 511
名媛妹妹
名媛妹妹 2020-12-19 13:46

I was writing code and I noticed some odd behavior in Groovy when I am dealing with XML and Maps. I thought about it and can\'t figure out why is it happening and should it

2条回答
  •  死守一世寂寞
    2020-12-19 14:02

    Here is a demonstration of this quirk of double quoted strings in Groovy:

    Double quoted strings are plain java.lang.String if there’s no interpolated expression, but are groovy.lang.GString instances if interpolation is present.

    groovy:000> m = [:]
    ===> {}
    groovy:000> tmp = "wat"
    ===> wat
    groovy:000> key = "${tmp}"
    ===> wat
    groovy:000> m << ["${key}": "hi"]
    ===> {wat=hi}
    groovy:000> m["${key}"] = "hi"
    ===> hi
    groovy:000> m
    ===> {wat=hi, wat=hi}
    groovy:000> m["wat"] = "fuuuuuu!"
    ===> fuuuuuu!
    groovy:000> m
    ===> {wat=hi, wat=fuuuuuu!}
    groovy:000> m.keySet().each { println it.class }
    class org.codehaus.groovy.runtime.GStringImpl
    class java.lang.String
    

    Enjoy ;)

提交回复
热议问题