views:

71

answers:

2

From the book "Groovy and Grails recipes" I'm using the following code snippet:

String HelloLanguage = "def hello(language) {return \"Hello $language\"}"

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?

+1  A: 

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\"}"

ccheneson
Thanks! That worked.
Maurits Rijk
A: 

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!
Vinny
The construct by itself looks a bit weird but actually isn't: it is used in an example that shows the use of the ScriptEngine class. The eval method of this class takes a string which contains a script.
Maurits Rijk