我很感激有人向我解释为什么以下情况属实:
def t = "test"
assert [test: 1] == ["test": 1] // 1. expected
assert ["$t": 1] != ["test": 1] // 2. unexpected
assert ["$t": 1] != [test: 1] // 3. unexpected
assert ["$t": 1] == ["$t": 1] // 4. expected
println ["$t": 1] // output: [test: 1]
println ["test": 1] // output: [test: 1]
我不明白为什么结果#2和#3存在不平等。
我在编写测试时遇到了这个问题,其中密钥在代码中动态创建,但考虑到测试条件,我知道它应该是字符串“test”。问题是返回的“看起来”是正确的,但不认为是相同的。我不明白为什么。
此外,以下“有效”:
def t = "test"
def odd = ["$t": 1]
assert !odd["$t"]
assert !odd.test
assert !odd["test"]
assert !odd."$t"
println odd // output: [test: 1]
def d = new Date()
def t2 = "$t"
def odd2 = [(t2): 1, (d): 2]
assert odd2[d] == 2
assert !odd2[d.toString()]
assert !odd2[t2] // expected 1
odd2.put(t2, 3)
println odd2 // output: [test: 3, /* date#toString */: 2]
assert odd.getAt(d) == 2
assert !odd2.getAt(t2) // expected 3
答案 0 :(得分:5)
添加这2行
assert "$t".class.simpleName == 'GStringImpl'
assert t.class.simpleName == 'String'
或只是
println "$t".class
println t.class
在第一行之后,您将能够理解为什么。 :)
如果您确实想使用t
的值,那么您应该使用as:
assert [(t): 1] == ["test": 1] //use (t) to use the variable value as key
assert [(t): 1] == [test: 1]
assert [(t): 1] != ["$t": 1]
更新
//String key as before, hence encouraged to use (t) instead of GStringImpl
def odd = [("$t".toString()): 1]
assert odd["$t"]
assert odd.test
assert odd["test"]
assert odd."$t"
//Equality by reference and by value in Groovy
assert "$t" == "test" //Value Equality == overridden in Groovy
assert !"$t".is("test") //Object Reference equality equivalent to == in Java