Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Groovy-GString用作键,String用作键,下标表示法用作put方法_Groovy_Gstring - Fatal编程技术网

Groovy-GString用作键,String用作键,下标表示法用作put方法

Groovy-GString用作键,String用作键,下标表示法用作put方法,groovy,gstring,Groovy,Gstring,在中,它提到使用GString作为密钥是不好的: def key = 'some key' def map = [:] def gstringKey = "${key.toUpperCase()}" map.put(gstringKey,'value') assert map.get('SOME KEY') == null 但是,只需将put()方法更改为使用下标表示法: def key = 'some key' def map = [:] def gstringKey = "${key.to

在中,它提到使用GString作为密钥是不好的:

def key = 'some key'
def map = [:]
def gstringKey = "${key.toUpperCase()}"
map.put(gstringKey,'value')
assert map.get('SOME KEY') == null
但是,只需将put()方法更改为使用下标表示法:

def key = 'some key'
def map = [:]
def gstringKey = "${key.toUpperCase()}"
map[gstringKey] = 'value' // here
assert map.get('SOME KEY') == null
足以导致断言失败。使用[]和put()方法的语义有什么不同?下标符号是否有某种对字符串的隐式转换?

下标符号是否有对字符串的隐式转换

基本上,是的

根据Groovy规则,语句
a[b]=c
相当于调用
a.putAt(b,c)
方法

的特定签名是
void putAt(String属性,Object newValue)
,这意味着如果
b
是一个Groovy字符串,那么它将首先使用其
toString()
方法转换为一个字符串


最后,
putAt
方法将使用
String
值作为键调用
Map.put

我不理解使用
GString
作为带有下标符号的映射键的问题。转换为
字符串
可能是人们想要的。Groovy文档应该警告不要使用
Map
get
put
方法。