GalloCedrone
GalloCedrone

Reputation: 5067

Groovy variable double substitution

I would like to perform double substitution.

When printing:

def y    = "\${x}"
def x    = "world"
def z    = "Hello ${y}"
println z

It prints:

Hello ${x}

When I would like it to print Hello World, I tried performing a double evaluation ${${}}, casting it to org.codehaus.groovy.runtime.GStringImpl, and a desperate ${y.toStrin()}

Edit:

To be more clear I mean this, but in Groovy:

(Why I am doing this?: Because we have some text files that we need evaluate with groovy variables; the variables are many and in different part of the code are different, therefore I would like to have a solution working across all cases, not to have to bind each time each variable, not adding many lines of code)

Upvotes: 0

Views: 585

Answers (2)

virtualdogbert
virtualdogbert

Reputation: 481

So with what you have you're escaping the $ so it is just interpreted as a string.

For what you are looking to do I would look into Groovys's templating engines: http://docs.groovy-lang.org/docs/next/html/documentation/template-engines.html

After reading your comment I played around with a few ideas and came up with this contrived answer, which is also probably not quite what you are looking for:

import groovy.lang.GroovyShell

class test{
    String x = "world"
    String y = "\${x}"
    void function(){
        GroovyShell shell = new GroovyShell();
        Closure c = shell.evaluate("""{->"Hello $y"}""")
        c.delegate = this
        c.resolveStrategry = Closure.DELEGATE_FIRST
        String z = c.call()
        println z
    }
}

new test().function()

But it was the closest thing I could come up with, and may lead you to something...

Upvotes: 2

emilles
emilles

Reputation: 1179

If I understand right, you are reading y from somewhere else. So you want to evaluate y as a GString after y and then x have been loaded. groovy.util.Eval will do this for simple cases. In this case, you have just one binding variable: x.

def y = '${x}'
def x = 'world'

def script = "Hello ${y}"
def z = Eval.me('x', x, '"' + script + '".toString()') // create a new GString expression from the string value of "script" and evaluate it to interpolate the value of "x"
println z

Upvotes: 1

Related Questions