0

As this post (Is there something like python's interactive REPL mode, but for Java?) shows, we can use groovysh for Java REPL.

I have this code that compiles well with javac.

    GroovyShell shell = new GroovyShell();
    shell.evaluate("println \"My name is ${name}\"");

However, when I tried to run this command in the groovysh, I got error. I had to make \${name} to bypass the error.

Why is this? What other possible (corner) cases that Java and Groovy code be different?

Community
  • 1
  • 1
prosseek
  • 182,215
  • 215
  • 566
  • 871

1 Answers1

3

Double quoted string literals in Groovy are GStrings, which interpret ${...} expressions and substitute their results into the string. Given the Groovy code

shell.evaluate("println \"My name is ${name}\"")

Groovy will try and resolve the name variable in the current context, and throw an exception when it fails to find a suitable definition.

If you want to pass the ${...} through literally (so it is interpreted by the GroovyShell rather than by the current Groovy context) then you either need to escape the dollar sign or use one of the other Groovy string delimiters that are not subject to ${...} interpolation (single quotes, triple-single-quotes, or slashes):

shell.evaluate('println "My name is ${name}"')
shell.evaluate('''println "My dog's name is ${dogName}"''')

In a single quoted string you also don't need to backslash the double quote characters.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183