最近我在Groovy的集合中使用GStringImpls vs Strings的行为.
我明白这个评估为假的原因
“${‘test’}”.equals(“test”)== false
是由于.equals()合同的对称性要求,但是我想知道是否有一个原因GStringImpl不能立即被评估为一个String.所以当我做这样的事情…
“${ ‘someString’}”
我没有得到一个GStringImpl,我只是得到一个简单的Java字符串回来,我可以立即用作地图中的键,例如.
我知道有一些解决方法,比如
String s =“${‘someString’}”
但是这样的东西有点不方便,而且GStringImpl和String之间的混合似乎对Groovy的新手来说是一个很大的“困难”.
由于某些原因,GStrings不会立即对String进行评估,主要涉及到懒惰评估(这对于日志记录是非常好的)和模板.在
Strings and GString你可以找到一个很好的解释:
GString
can involve lazy evaluation so it’s not until the toString()
method is invoked that the GString is evaluated. This lazy evaluation
is useful for things like logging as it allows the calculation of the
string,the calls to toString() on the values,and the concatenation
of the different strings to be done lazily if at all.
GString is pretty handy when you don’t want to use a template engine,
or when you really want full lazy evaluation of GStrings. When some
variable embedded in a GString,the toString() is called on that
variable to get a string representation,and it’s inserted into the
final string.
因此:
GString and String are two distinct classes,and hence use of GString
objects as keys for Map objects or comparisons involving GString
objects,can produce unexpected results when combined with String
objects since a GString and a String won’t have the same hashCode nor
will they be equal. There is no automatic coercion between the two
types for comparisons or map keys,so it’s sometimes necessary to
explicitly invoke toString() on GString objects.
Unexpected conversion to String can lead to problems when code is expecting a GString,as for methods in groovy.sql classes.