I feel like I'm missing something with how Groovy handles strings. I realize that they're immutable, but what I would like to do is interpolate a value at runtime. I can't figure out how. Let me give a really simple example in Python (as "executable pseudo-code") to illustrate what I mean. Then I'll give what I've tried in Groovy.
Python
# string_sample.py
class MyClass(object):
greeting = 'Hello, %s!'
def __init__(self):
object.__init__(self)
def sayHello(self, name):
print self.greeting % name
if __name__ == '__main__':
m = MyClass()
m.sayHello('Mario')
The above prints: Hello, Mario!
Groovy
// string_sample.groovy
class MyClass {
def greeting = "Hello, ${name}!"
MyClass() {
}
void sayHello(name) {
println greeting
}
}
m = new MyClass()
m.sayHello('Mario')
The above Groovy script complains that name
is unknown:
Caught: groovy.lang.MissingPropertyException: No such property: name for class: MyClass
I understand what's happening and why. I'm just not sure what to do about it. I realize that String.format
can be used, which isn't so bad:
String greeting = "Hello, %s!"
// Omitted...
void sayHello(name) {
println String.format(greeting, name)
}
I'm just thinking that maybe there's a groovier way of doing it. Anyone know? Thanks!