加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Groovy GStringImpl和String行为

发布时间:2020-12-14 16:30:47 所属栏目:大数据 来源:网络整理
导读:最近我在Groovy的集合中使用GStringImpls vs Strings的行为. 我明白这个评估为假的原因 “${‘test’}”.equals(“test”)== false 是由于.equals()合同的对称性要求,但是我想知道是否有一个原因GStringImpl不能立即被评估为一个String.所以当我做这样的事情
最近我在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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读