Variable reference in a Groovy GString
From the book "Groovy and Grails recipes" I'm using the following code snippet:
String HelloLanguage = "def hello(language) {return \"Hello $lan开发者_StackOverflow社区guage\"}"
However, I get a compiler error "You attempted to reference a variable in the binding or an instance variable from a static context." because language can't be bound. What is wrong?
I m not too familiar with Groovy I just tried your string in the GroovyConsole and I got an Exception - After escaping the dollar, it ran fine. Could it be it?
String HelloLanguage = "def hello(language) {return \"Hello \$language\"}"
This is a strange construct. Unfortunately I don't have the book but it looks like you are making a string of what looks like a method definition. Taking that to the logical next step, a basic groovy class might look something like this
class Talker {
def hello(language) { return "Hello ${language} !" }
}
def talker = new Talker()
talker.hello("English") // prints: Hello English!
精彩评论