开发者

Dynamic GString creation doesn't not work as I expect

开发者 https://www.devze.com 2023-02-26 18:36 出处:网络
I have the following code: def test( name) { s = [\'$\',\'{\',\'n\',\'a\',\'m\',\'e\',\'}\'].join() println s instanceof String // is true, s is not a gstring

I have the following code:

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")

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}"
    print开发者_如何转开发ln g instanceof GString // is true
    println g.toString()   
}
test("Oscar")

I think I know the reason but I would like to know for sure.


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?


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.

def myFunction()  {
  def a = 1
  return '${a}'
}

GString.EMPTY.plus (myFunction()) // no access to local variable a anymore!

thus, no evaluation happens on a given java.lang.String on a GString.plus call.

0

精彩评论

暂无评论...
验证码 换一张
取 消