动态 GString 创建无法按我的预期工作
我有以下代码:
def test( name ) {
s = ['$','{','n','a','m','e','}'].join()
println s instanceof String // is true, s is not a gstring
// create a GString
g = GString.EMPTY.plus( s )
println g instanceof GString
println g.toString() // Shouldn't evaluate here?
}
test("Oscar")
我希望输出为:
true
true
Oscar
但我有:
true
true
${name}
我知道我可以使用以下方法实现这一目标:
def test( name ) {
g = "${name}"
println g instanceof GString // is true
println g.toString()
}
test("Oscar")
我认为 我知道原因,但我想确定。
I have the following code:
def test( name ) {
s = ['
I expect the output to be:
true
true
Oscar
But instead I have:
true
true
${name}
I know I can achieve that using:
def test( name ) {
g = "${name}"
println g instanceof GString // is true
println g.toString()
}
test("Oscar")
I think I know the reason but I would like to know for sure.
,'{','n','a','m','e','}'].join()
println s instanceof String // is true, s is not a gstring
// create a GString
g = GString.EMPTY.plus( s )
println g instanceof GString
println g.toString() // Shouldn't evaluate here?
}
test("Oscar")
I expect the output to be:
But instead I have:
I know I can achieve that using:
I think I know the reason but I would like to know for sure.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您将 g 和 s 都声明为字符串,因此 toString() 方法将仅返回它们的值。没有对 Groovy 代码进行实际评估(如果您考虑一下,这在很多情况下可能是危险的)。
我认为无论你想要实现什么目标,通过闭包都可以更好地完成?
Since you declare both g and s to be strings, the toString() method will simply return their values. There is no actual evaluation of Groovy code (this could be dangerous in quite a few scenarios, if you think about it).
I think whatever you're trying to achieve might be better accomplished via closures?
原因是 Groovy 无法确保它仍然可以访问创建 java.lang.String 的上下文,例如
,在 GString.plus 调用上不会对给定的 java.lang.String 进行求值。
the reason is that Groovy can't ensure it still has access to the context where the java.lang.String has been created e.g.
thus, no evaluation happens on a given java.lang.String on a GString.plus call.