Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy string interpolation with value only known at runtime

Tags:

groovy

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!

like image 811
Mario Avatar asked Mar 11 '15 21:03

Mario


People also ask

What is ${} in Groovy?

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 ${} .

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

How do I pass a string in Groovy?

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.

How do I print a value in Groovy script?

You can print the current value of a variable with the println function.


1 Answers

You could use a closure:

class MyClass {

    def greeting = { name -> "Hello, ${name}!" }

    MyClass() {
    }

    void sayHello(name) {
        println greeting(name)
    }
}
like image 52
tim_yates Avatar answered Oct 06 '22 08:10

tim_yates