OscarRyz
OscarRyz

Reputation: 199215

Dynamic GString creation doesn't not work as I expect

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}"
    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.

Upvotes: 1

Views: 643

Answers (2)

Andre Steingress
Andre Steingress

Reputation: 4411

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.

Upvotes: 1

Igor
Igor

Reputation: 33973

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?

Upvotes: 1

Related Questions