In Groovy, is it possible to define variables as template first then use them later?
Like predefine body
before knowing the content of subject
:
body = 'Hello, ${subject}!'
subject = "World"
Then get Hello, World!
from the body
template (after the content of subject
is defined) somehow?
You can use a closure inside a GString
, so instead of capturing the value on creation of the GString
, it gets evaluated when it has to manifest into a string.
body = "Hello, ${-> subject}!"
subject = "World"
println body
// → Hello, World!