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!
String interpolation. Any Groovy expression can be interpolated in all string literals, apart from single and triple-single-quoted strings. Interpolation is the act of replacing a placeholder in the string with its value upon evaluation of the string. The placeholder expressions are surrounded by ${} .
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
Groovy Programming Fundamentals for Java DevelopersStrings in Groovy can be enclosed in single quotes ('), double quotes (“), or triple quotes (“””). Further, a Groovy String enclosed by triple quotes may span multiple lines.
You can print the current value of a variable with the println function.
You could use a closure:
class MyClass {
def greeting = { name -> "Hello, ${name}!" }
MyClass() {
}
void sayHello(name) {
println greeting(name)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With